Skip to content

Instantly share code, notes, and snippets.

@Kami
Created May 27, 2012 07:23
Show Gist options
  • Select an option

  • Save Kami/2802590 to your computer and use it in GitHub Desktop.

Select an option

Save Kami/2802590 to your computer and use it in GitHub Desktop.
Swiz - serialization example
var swiz = require('swiz');
var O = swiz.struct.Obj;
var F = swiz.struct.Field;
var defs = [
O('Server',
{
'fields': [
F('id', {'src': 'hash_id', 'desc': 'hash ID for the server', 'attribute': true}),
F('is_active', {'src': 'active', 'desc': 'is the server active?', 'coerceTo': 'boolean'}),
F('name', {'src' : 'get_name', 'desc' : 'name', 'attribute': true}),
F('agent_name'),
F('ipaddress' , {'src' : 'get_public_address'}),
F('public_ips', {'singular': 'ip', 'filterFrom': ['public'], 'coerceTo': 'array'}),
F('state', {'enumerated' : {inactive: 0, active: 1}, 'filterFrom': ['public']}),
F('opts', {'src': 'options'}),
F('data')
],
'plural': 'servers'
}),
O('ServerOpts',
{
'fields': [
F('option1', {'src': 'opt1'}),
F('option2', {'src': 'opt2'}),
F('option3', {'src': 'opt3'}),
],
'singular': 'serverOpts'
})
];
function Server() {
this.hash_id = '15245';
this.active = true;
this.agent_name = 'some agent';
this.public_ips = ['123.45.55.44', '122.123.32.2'];
this.state = 1;
this.options = {
'opt1': 'defaultval',
'opt2': 'defaultval',
'opt3': function(callback) {
callback(null, 'something');
}
};
this.some_attribute_1 = 'a';
this.some_attribute_1 = 'b';
this.options.getSerializerType = function() {
return 'ServerOpts';
};
this.data = {
'foo': 'thingone',
'bar': 'thingtwo'
};
}
Server.prototype.get_name = function(callback) {
callback(null, 'server #1');
};
Server.prototype.getSerializerType = function() {return 'Server';};
var server = new Server();
var sw1 = new swiz.Swiz(defs, {'stripNulls': false});
var sw2 = new swiz.Swiz(defs, {'for': 'public', stripNulls: false});
sw1.serialize(swiz.SERIALIZATION.SERIALIZATION_JSON, 1, server, function(err, serialized) {
console.log('JSON:');
console.log(serialized);
});
sw1.serialize(swiz.SERIALIZATION.SERIALIZATION_XML, 1, server, function(err, serialized) {
console.log('XML:');
console.log(serialized);
});
sw2.serialize(swiz.SERIALIZATION.SERIALIZATION_JSON, 1, server, function(err, serialized) {
console.log('JSON (for public):');
console.log(serialized);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment