UNPKG

1.42 kBJavaScriptView Raw
1/**
2 * @function apemanAppJson
3 * @param {object} [options] - Optional settings.
4 * @param {number} [options.spaces=2] - JSON spaces
5 * @param {string} [options.contentType='application/json charset=UTF-8'] - Content type for header
6 * @param {string} [options.name='json'] - Property name of response to set the function.
7 * @returns {function} - Defined app function.
8 */
9
10'use strict'
11
12const argx = require('argx')
13const objnest = require('objnest')
14
15/** @lends create */
16function create (options) {
17 let args = argx(arguments)
18 options = objnest.expand(args.pop('object') || {})
19
20 let spaces = options.spaces || 2
21 let contentType = options.contentType || 'application/json charset=UTF-8'
22 let name = options.name || 'json'
23
24 function json (data) {
25 if (typeof data === 'string') {
26 data = JSON.parse(data)
27 }
28 let res = this
29 let body = JSON.stringify(data, null, spaces)
30 res.setHeader('Content-Length', Buffer.byteLength(body))
31 res.setHeader('Content-Type', contentType)
32 res.end(body)
33 }
34
35 /**
36 * Defined app.
37 * @function app
38 * @param {object} req - Request object.
39 * @param {object} res - Response object.
40 * @param {function} next - Pass to next handler.
41 */
42 function app (req, res, next) {
43 res[ name ] = res[ name ] || json
44 next()
45 }
46
47 // Description of this app.
48 app.$desc = 'Define json response function.'
49 return app
50}
51
52module.exports = create