This repository has been archived by the owner on Sep 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
json-handler.js
76 lines (73 loc) · 2.54 KB
/
json-handler.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
66
67
68
69
70
71
72
73
74
75
76
/**
* MOST Web Framework
* A JavaScript Web Framework
* http://themost.io
*
* Copyright (c) 2014, Kyriakos Barbounakis k.barbounakis@gmail.com, Anthi Oikonomou anthioikonomou@gmail.com
*
* Released under the BSD3-Clause license
* Date: 2014-12-02
*/
/**
* @ignore
*/
var bodyParser = require('body-parser'), jsonParser;
var _ = require('lodash');
function JsonHandler() {
}
var DateTimeRegex = /^(\d{4})(?:-?W(\d+)(?:-?(\d+)D?)?|(?:-(\d+))?-(\d+))(?:[T ](\d+):(\d+)(?::(\d+)(?:\.(\d+))?)?)?(?:Z(-?\d*))?([+-](\d+):(\d+))?$/g;
function reviveDates(key, value){
var match;
if (typeof value === "string" && DateTimeRegex.test(value) ) {
return new Date(value);
}
return value;
}
JsonHandler.prototype.beginRequest = function(context, callback) {
var request = context.request, response = context.response;
request.headers = request.headers || {};
var contentType = request.headers['content-type'];
if (/^application\/json/i.test(contentType)) {
//change: 15-Feb 2016
//description get json body limit from application configuration (settings#json.limit)
if (typeof jsonParser === 'undefined') {
//ensure settings
context.application.config.settings = context.application.config.settings || { };
//ensure json settings (the default limit is 100kb)
context.application.config.settings.json = context.application.config.settings.json || { limit:102400 };
//get json parser
jsonParser = bodyParser.json(_.assign(context.application.config.settings.json, {
reviver:reviveDates
}));
}
//parse request data
jsonParser(request, response , function(err) {
if (err) {
callback(err);
}
else {
try {
if (request.body) {
//try parse
if (request.body instanceof Buffer) {
context.params.data = JSON.parse(request.body);
}
else if (typeof request.body === 'object') {
context.params.data = request.body;
}
callback();
}
}
catch(e) {
callback(e);
}
}
});
}
else {
callback();
}
};
if (typeof exports !== 'undefined') {
module.exports.createInstance = function() { return new JsonHandler(); };
}