-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathjson.js
51 lines (37 loc) · 985 Bytes
/
json.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
'use strict';
// var stringify = require('json-stringify-safe')
var extend = require('xtend');
var send = require('./index')
var isSendObject = require('./is-send-object')
var CONTENT_TYPE_HEADER = {
'content-type': 'application/json'
}
module.exports = sendJson
function sendJson(req, res, opts, callback) {
if (!isSendObject(opts)) {
opts = { body: opts }
} else {
opts = extend(opts);
}
if (opts.pretty) {
opts.space = ' '
}
var tuple = safeStringify(opts.body,
opts.replacer || null, opts.space || '');
if (tuple[0]) {
return callback(tuple[0]);
}
opts.headers = extend(opts.headers, CONTENT_TYPE_HEADER);
opts.body = tuple[1];
send(req, res, opts, callback)
}
function safeStringify(obj, replace, space) {
var json;
var error = null;
try {
json = JSON.stringify(obj, replace, space);
} catch (e) {
error = e;
}
return [error, json];
}