1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | 'use strict'
|
11 |
|
12 | const argx = require('argx')
|
13 | const objnest = require('objnest')
|
14 |
|
15 |
|
16 | function 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 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 | function app (req, res, next) {
|
43 | res[ name ] = res[ name ] || json
|
44 | next()
|
45 | }
|
46 |
|
47 |
|
48 | app.$desc = 'Define json response function.'
|
49 | return app
|
50 | }
|
51 |
|
52 | module.exports = create
|