-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
65 lines (55 loc) · 1.4 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*!
* msgpack-response
* Copyright(c) 2017-present Mobiltron Inc
* MIT Licensed
*/
/**
* Module dependencies.
*/
const _ = require('lodash');
const msgpack = require('msgpack');
/**
* Transform response data using msgpack.
*
* @return {Function} middleware
* @public
*/
function mgsPackResponse(options) {
let autoDetect = false;
if (!_.isUndefined(options)) {
autoDetect = options.auto_detect || false;
}
return function _mgsPackResponse(req, res, next) {
if (shouldMsgPack(req) && autoDetect) {
res.json = function(jsObject) {
var obj = jsObject;
var encodedResponse = msgpack.pack(obj);
res.setHeader('Content-Type', 'application/x-msgpack');
res.removeHeader('Content-Length');
res.setHeader('Content-Length', _.size(encodedResponse));
res.send(encodedResponse);
}
}
res.msgPack = function(jsObject) {
var obj = jsObject;
var encodedResponse = msgpack.pack(obj);
res.setHeader('Content-Type', 'application/x-msgpack');
res.setHeader('Content-Length', _.size(encodedResponse));
res.send(encodedResponse);
};
next();
};
}
/**
* Default filter function.
* @private
*/
function shouldMsgPack(req) {
let acceptType = req.get('accept');
return !_.isNil(acceptType) && acceptType === 'application/x-msgpack';
}
/**
* Module exports.
* @public
*/
module.exports = mgsPackResponse;