1 | "use strict";
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | Object.defineProperty(exports, "__esModule", { value: true });
|
19 | const _ = require("lodash");
|
20 | const express = require("express");
|
21 | const index_1 = require("../index");
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 | function jsonObject(optsOrSchema) {
|
30 | let opts;
|
31 | if (optsOrSchema) {
|
32 | if (optsOrSchema['isJoi']) {
|
33 | opts = {
|
34 | schema: optsOrSchema,
|
35 | };
|
36 | }
|
37 | else {
|
38 | opts = optsOrSchema;
|
39 | }
|
40 | }
|
41 | if (!opts) {
|
42 | opts = {};
|
43 | }
|
44 | let failedHandler = opts.failedHandler;
|
45 | if (!failedHandler) {
|
46 |
|
47 | failedHandler = (ctx) => {
|
48 | const RESULT = {
|
49 | success: false,
|
50 | data: {
|
51 | details: ctx.details,
|
52 | reason: ctx.reason,
|
53 | },
|
54 | };
|
55 | return ctx.response
|
56 | .status(400)
|
57 | .header('content-type', 'application/json; charset=utf-8')
|
58 | .send(Buffer.from(JSON.stringify(RESULT), 'utf8'));
|
59 | };
|
60 | }
|
61 | const HANDLERS = [];
|
62 | HANDLERS.push(express.json(opts.options));
|
63 | if (opts.schema) {
|
64 | HANDLERS.push(async function (req, res, next) {
|
65 | let reason = 'no_object';
|
66 | let details;
|
67 | const BODY = req.body;
|
68 | if (_.isNull(BODY) && index_1.toBooleanSafe(opts.canBeNull)) {
|
69 | return next();
|
70 | }
|
71 | if (_.isUndefined(BODY) && index_1.toBooleanSafe(opts.canBeUndefined)) {
|
72 | return next();
|
73 | }
|
74 | if (_.isObjectLike(BODY)) {
|
75 | reason = 'invalid_structure';
|
76 | const JSON_VALIDATION = opts.schema.validate(BODY);
|
77 | if (_.isNil(JSON_VALIDATION.error)) {
|
78 | return next();
|
79 | }
|
80 | else {
|
81 | details = JSON_VALIDATION.error.message;
|
82 | }
|
83 | }
|
84 | return await Promise.resolve(failedHandler({
|
85 | body: BODY,
|
86 | details: details,
|
87 | reason: reason,
|
88 | request: req,
|
89 | response: res,
|
90 | }));
|
91 | });
|
92 | }
|
93 | else {
|
94 |
|
95 | HANDLERS.push(async function (req, res, next) {
|
96 | let reason = 'no_object';
|
97 | let details;
|
98 | const BODY = req.body;
|
99 | if (_.isNull(BODY) && index_1.toBooleanSafe(opts.canBeNull)) {
|
100 | return next();
|
101 | }
|
102 | if (_.isUndefined(BODY) && index_1.toBooleanSafe(opts.canBeUndefined)) {
|
103 | return next();
|
104 | }
|
105 | if (_.isObjectLike(BODY)) {
|
106 | return next();
|
107 | }
|
108 | details = `Request body is of type '${_.isNull(BODY) ? 'null' : (typeof BODY)}'`;
|
109 | return await Promise.resolve(failedHandler({
|
110 | body: BODY,
|
111 | details: details,
|
112 | reason: reason,
|
113 | request: req,
|
114 | response: res,
|
115 | }));
|
116 | });
|
117 | }
|
118 | return HANDLERS;
|
119 | }
|
120 | exports.jsonObject = jsonObject;
|
121 |
|
\ | No newline at end of file |