This repository has been archived by the owner on Aug 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
51 lines (43 loc) · 1.18 KB
/
index.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
'use strict';
// Copyright 2012 Mark Cavage, Inc. All rights reserved.
function formatJSONP(request, response, body) {
var formattedResponse;
try {
formattedResponse = formatResponse(request, body);
} catch (e) {
formattedResponse = null;
}
setContentLength(formattedResponse, response);
return formattedResponse;
}
function formatResponse(request, body) {
body = validateBody(body);
return wrapJSONP(request, body);
}
function validateBody(body) {
if (!body) {
throw new Error('body is null');
}
body = body instanceof Error ? error2body(body) : body;
body = Buffer.isBuffer(body) ? body.toString('base64') : body;
return body;
}
function error2body(body) {
return ((body.restCode || body.httpCode) && body.body) ?
body.body :
{
message: body.message
};
}
function wrapJSONP(req, body) {
var jsonpCallback;
body = JSON.stringify(body);
jsonpCallback = req.query.callback || req.query.jsonp;
return jsonpCallback ?
jsonpCallback + '(' + body + ');' : body;
}
function setContentLength(data, response) {
var length = data ? Buffer.byteLength(data) : 0;
response.setHeader('Content-Length', length);
}
module.exports = formatJSONP;