periodicjs.core.responder
Description
Core responder is a component of periodicjs.core.controller that provides adapters for different formatting responses across different content types. Each adapter may have options specific to the content type, but after being constructed the same methods are exposed. Depending on content type adapters do everything from wrapping JSON data in a standard way to rendering HTML from templates.
Usage (basic)
const AdapterInterface = require('periodicjs.core.responder');
var adapter = AdapterInterface.create({ adapter: 'json' });
adapter.render({ foo: 'bar' })
.then(result => {
});
adapter.render({ foo: 'bar' }, (err, result) => {
});
let result = adapter.render({ foo: 'bar' }, { sync: true });
let result = adapter.render({ foo: 'bar' }, {
formatRender: function (data, options) {
return {
custom: 'field',
data
};
}
});
adapter = AdapterInterface.create({ adapter: 'xml', xml_root: 'example' });
adapter.render({ foo: 'bar' })
.then(result => {
});
adapter.render({ foo: 'bar' }, {
declaration: { encoding: 'UTF-8' }
}, (err, result) => {
});
adapter = AdapterInterface.create({ adapter: 'html', viewname: 'user.ejs' });
adapter.render({ user: 'Jim' })
.then(result => {
});
adapter = AdapterInterface.create({ adapter: 'html', viewname: 'user.pug', engine: require('pug') });
adapter.render({ user: 'Jim' })
.then(result => {
});
Usage (HTML Adapter Advanced)
const AdapterInterface = require('periodicjs.core.responder');
const mustache = require('mustache');
const path = require('path');
var render = mustache.render.bind(mustache);
mustache.render = function (template, data, options) {
mustache.parse(template);
return render(template, data, options);
};
const adapter = AdapterInteraface.create({ adapter: 'html', engine: mustache, viewname: 'user.mustache' });
adapter.render({ user: 'Jim' }, { dirname: '/some/path/to/dir' })
.then(result => {
});
Usage (with custom adapter)
const AdapterInterface = require('periodicjs.core.responder');
const template = function (data) {
return `Hello ${ data }!`;
};
const CustomAdapter = class {
constructor (options) {
...
},
render (data, options) {
return template(data);
},
error (err, options) {
return `There was an error: ${ err.message } :(`;
}
};
var adapter = AdapterInterface.create({ adapter: CustomAdapter });
adapter.render('Jim');
Development
Make sure you have grunt installed
$ npm install -g grunt-cli jsdoc-to-markdown
For generating documentation
$ grunt doc
$ jsdoc2md adapters/**/*.js index.js > doc/api.md
Notes
Testing
$ npm i
$ grunt test
Contributing
License
MIT