UNPKG

2.51 kBJavaScriptView Raw
1/**
2 * MOST Web Framework
3 * A JavaScript Web Framework
4 * http://themost.io
5 *
6 * Copyright (c) 2014, Kyriakos Barbounakis k.barbounakis@gmail.com, Anthi Oikonomou anthioikonomou@gmail.com
7 *
8 * Released under the BSD3-Clause license
9 * Date: 2014-12-02
10 */
11var bodyParser = require('body-parser'), jsonParser;
12var UnknownValue = require('./post').UnknownValue;
13var _ = require('lodash');
14
15function reviveDates(key, value){
16 if (typeof value === "string" && UnknownValue.DateTimeRegex.test(value) ) {
17 return new Date(value);
18 }
19 return value;
20}
21/**
22 * @class
23 * @constructor
24 * @implements BeginRequestHandler
25 */
26function JsonHandler() {
27
28}
29
30JsonHandler.prototype.beginRequest = function(context, callback) {
31 var request = context.request, response = context.response;
32 request.headers = request.headers || {};
33 var contentType = request.headers['content-type'];
34 if (/^application\/json/i.test(contentType)) {
35 //change: 15-Feb 2016
36 //description get json body limit from application configuration (settings#json.limit)
37 if (typeof jsonParser === 'undefined') {
38 //get application settings
39 var settings = context.getApplication().getConfiguration().settings;
40 //ensure json settings (the default limit is 100kb)
41 settings.json = settings.json || { limit:102400 };
42 //get json parser
43 jsonParser = bodyParser.json(_.assign(settings.json, {
44 reviver:reviveDates
45 }));
46 }
47 //parse request data
48 jsonParser(request, response , function(err) {
49 if (err) {
50 callback(err);
51 }
52 else {
53 try {
54 if (request.body) {
55 //try parse
56 if (request.body instanceof Buffer) {
57 context.params.data = JSON.parse(request.body);
58 }
59 else if (typeof request.body === 'object') {
60 context.params.data = request.body;
61 }
62 callback();
63 }
64 }
65 catch(e) {
66 callback(e);
67 }
68
69 }
70 });
71 }
72 else {
73 callback();
74 }
75};
76if (typeof exports !== 'undefined') {
77 module.exports.JsonHandler = JsonHandler;
78 module.exports.createInstance = function() { return new JsonHandler(); };
79}
\No newline at end of file