Datamodel
Design datamodels with asynchronous functions and flows.
Contributors
Installation
With npm do:
$ npm install datamodel
Tests
Use mocha to run the tests.
$ npm install mocha
$ mocha test
Examples
Example 1 : Create a datamodel with 3 files and 1 directory
var fs = require('fs')
, datamodel = require('datamodel');
datamodel()
.declare('dirname', function(input, fill) {
fill('/etc');
})
.prepend('file1', function(input, fill) {
fs.readFile(this.dirname + '/group', function (err, data) {
fill(err ? err : data.toString().substring(0, 7).concat('...'));
});
})
.append('file2', function(input, fill) {
fs.readFile(this.dirname + '/hosts', function (err, data) {
fill(err ? err : data.toString().substring(0, 7).concat('...'));
});
})
.append('file3', function(input, fill) {
fs.readFile(this.dirname + '/unknown', function (err, data) {
fill(err ? err : data.toString().substring(0, 7).concat('...'));
});
})
.apply(function(err, res) {
console.error('Error>', err);
console.log('Result>', res);
});
output
Error> { [Error: Some fields are errors.] fields: [ 'file3' ] }
Result> { dirname: '/etc',
file1: 'root:x:...',
file2: '127.0.0...',
file3: { [Error: ENOENT, open '/etc/unknown'] errno: 34, code: 'ENOENT', path: '/etc/unknown' } }
Example 2 : Declare a datamodel as package/module
obj.js
var datamodel = require('datamodel');
datamodel()
.declare('a', function(input, fill) {
fill(input + 'A');
})
.append('b.1', function(input, fill) {
fill(input + 'B1');
})
.append('b.2', function(input, fill) {
fill(input + 'B1');
})
.append('b.3', function(input, fill) {
fill(input + 'B3');
})
.complete('c', function(input, fill) {
fill(input + 'C');
})
.attach(module);
index.js
var util = require('util');
require('./obj.js')('#', function(o) {
console.log(util.inspect(o, { colors:true, depth: null }));
}
);
Output
{ a: '#A',
'b.1': '#B1',
'b.2': '#B1',
'b.3': '#B3',
c: '#C' }
Example 3 : Combine a datamodel and a route with Express
var app = require('express');
app.route('/resource/:param1/:param2').all(require('./obj.js'));
API Documentation
datamodel()
declare(String key, Function callback)
prepend(String key, Function callback)
append(String key, Function callback)
complete(String key, Function callback)
transform(Function callback)
You can only call transform
once.
So, if you need to apply two transforms, put them both in the same transform callback.
Example:
return datamodel()
.append('years', function(req, fill) {
coll
.aggregate(
{ $project: { Py: 1, _id: 0} },
{ $group: { _id: "$Py", occ: { $sum: 1} } })
.then(fill)
.catch(fill);
})
.transform(function(req, fill) {
var n = this;
var y = {};
this.years.each(function (e) {
y[e._id] = e.occ;
});
n.years = y;
fill(n);
})
send(Function callback)
apply(Mixed input, Mixed output, Function callback)
attach(Object module)
License
MIT/X11