apeman-app-json
Version:
apeman app to serve dynamic json.
49 lines (42 loc) • 1.31 kB
JavaScript
/**
* @function apemanAppJson
* @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.
*/
/** @lends create */
function create (options = {}) {
let spaces = options.spaces || 2
let contentType = options.contentType || 'application/json charset=UTF-8'
let name = options.name || 'json'
function json (data) {
if (typeof data === 'string') {
data = JSON.parse(data)
}
const res = this
let 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()
}
Object.assign(app, {
// Description of this app.
$desc: 'Define json response function.'
})
return app
}
module.exports = create