wzp
2021-05-13 7d694a9113118daec5be7ac224dab46a3b20f106
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
// Copyright 2012 Mark Cavage, Inc.  All rights reserved.
 
'use strict';
 
var errors = require('restify-errors');
 
///--- Exports
 
/**
 * JSON formatter. Will look for a toJson() method on the body. If one does not
 * exist then a JSON.stringify will be attempted.
 *
 * @public
 * @function formatJSON
 * @param    {Object} req - the request object (not used)
 * @param    {Object} res - the response object
 * @param    {Object} body - response body
 * @returns  {String} data
 */
function formatJSON(req, res, body) {
    var data = 'null';
    if (body) {
        try {
            data = JSON.stringify(body);
        } catch (e) {
            throw new errors.InternalServerError(
                { cause: e, info: { formatter: 'json' } },
                'could not format response body'
            );
        }
    }
 
    // Setting the content-length header is not a formatting feature and should
    // be separated into another module
    res.setHeader('Content-Length', Buffer.byteLength(data));
 
    return data;
}
 
module.exports = formatJSON;