0.4.1 • Published 10 years ago

castly v0.4.1

Weekly downloads
3
License
-
Repository
github
Last release
10 years ago

#castly

Javascript unmarshalling. Copies generic JSON attributes into "fresh" instances complete with methods and prototypes. Easily describe what you expect to come back from the server and it will optionally log or throw when it doesn't match.

Build Status

Installation

$ npm install is-a

Usage

var myJSON = JSON.stringify({
    tuple:[1, 2, "three"],
    flag: true,
    config1: {
        a:true,
        b:false
    },
    config2: {
        a:true,
        b:false,
        c:true
    }
});


function myConstructor() {
    this.describeType = function () {
        return {
            tuple: SpecialTuple,
            flag: typeIs.BOOLEAN,
            config1: Config,
            config2: Config
        };
    };
}

function Config() {
    this.describeType = function () {
        return {
            a: typeIs.BOOLEAN,
            b: typeIs.BOOLEAN,
            c: [typeIs.BOOLEAN, typeIs.UNDEFINED]
        };
    };
    this.do_stuff = function() {
        console.log(this.a && this.b || this.c)
    }
}

function SpecialTuple() {
    this.describeType = function () {
        this.length = 3;
        return function(obj, name, attr) {
            if(attr === '0') return castly.convert(obj, typeIs.NUMBER, name + "[0]");
            if(attr === '1') return castly.convert(obj, typeIs.NUMBER, name + "[1]");
            if(attr === '2') return castly.convert(obj, typeIs.STRING, name + "[2]");
            else return castly.convert(obj, typeIs.UNDEFINED, name + "[" + attr + "]");
        }
    };
    this.toString = function() {
        return "I'm a special tuple " + this.join("---");
    }
}
SpecialTuple.prototype = [];



var castly = require('../index');
var typeIs = castly.typeIs;
castly.strict = true;

var myObj = castly.unmarshal(myJSON, myConstructor);
console.log(myObj.tuple.toString());  //"I'm a special tuple 1---2---three"
myObj.config1.do_stuff(); //"undefined"
myObj.config2.do_stuff(); //"true"
0.4.1

10 years ago

0.4.0

10 years ago

0.3.2

10 years ago

0.3.1

10 years ago

0.3.0

10 years ago

0.2.0

10 years ago

0.1.1

10 years ago

0.1.0

10 years ago

0.0.3

10 years ago

0.0.2

10 years ago

0.0.1

10 years ago

0.0.0

10 years ago