1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | var bodyParser = require('body-parser'), jsonParser;
|
12 | var UnknownValue = require('./post').UnknownValue;
|
13 | var _ = require('lodash');
|
14 |
|
15 | function reviveDates(key, value){
|
16 | if (typeof value === "string" && UnknownValue.DateTimeRegex.test(value) ) {
|
17 | return new Date(value);
|
18 | }
|
19 | return value;
|
20 | }
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | function JsonHandler() {
|
27 |
|
28 | }
|
29 |
|
30 | JsonHandler.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 |
|
36 |
|
37 | if (typeof jsonParser === 'undefined') {
|
38 |
|
39 | var settings = context.getApplication().getConfiguration().settings;
|
40 |
|
41 | settings.json = settings.json || { limit:102400 };
|
42 |
|
43 | jsonParser = bodyParser.json(_.assign(settings.json, {
|
44 | reviver:reviveDates
|
45 | }));
|
46 | }
|
47 |
|
48 | jsonParser(request, response , function(err) {
|
49 | if (err) {
|
50 | callback(err);
|
51 | }
|
52 | else {
|
53 | try {
|
54 | if (request.body) {
|
55 |
|
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 | };
|
76 | if (typeof exports !== 'undefined') {
|
77 | module.exports.JsonHandler = JsonHandler;
|
78 | module.exports.createInstance = function() { return new JsonHandler(); };
|
79 | } |
\ | No newline at end of file |