apeman-app-json
Version:
apeman app to serve dynamic json.
56 lines (46 loc) • 1.59 kB
JavaScript
/**
* apeman app to send json response.
* @memberof module:apeman-app-json/lib
* @function create
* @param {object} [options] - Optional settings.
* @param {number} [options.spaces=2] - JSON spaces
* @param {string} [options.contentType='application/json; charset=UTF-8;'] - Content type for header
* @param {string} [options.name='json'] - Property name of response to set the function.
* @returns {function} - Defined app function.
*/
;
var argx = require('argx'),
objnest = require('objnest');
/** @lends create */
function create(options) {
var args = argx(arguments);
options = objnest.expand(args.pop('object') || {});
var spaces = options.spaces || 2,
contentType = options.contentType || 'application/json; charset=UTF-8;',
name = options.name || 'json';
function json(data) {
if (typeof(data) === 'string') {
data = JSON.parse(data);
}
var res = this,
body = JSON.stringify(data, null, spaces);
res.setHeader('Content-Length', Buffer.byteLength(body));
res.setHeader('Content-Type', contentType);
res.end(body);
}
/**
* Defined app.
* @function app
* @param {object} req - Request object.
* @param {object} res - Response object.
* @param {function} next - Pass to next handler.
*/
function app(req, res, next) {
res[name] = res[name] || json;
next();
}
// Description of this app.
app.$desc = "Define json response function.";
return app;
}
module.exports = create;