UNPKG

2.93 kBJavaScriptView Raw
1"use strict";
2// Copyright IBM Corp. and LoopBack contributors 2018,2020. All Rights Reserved.
3// Node module: @loopback/rest
4// This file is licensed under the MIT License.
5// License text available at https://opensource.org/licenses/MIT
6Object.defineProperty(exports, "__esModule", { value: true });
7exports.Validator = void 0;
8const __1 = require("../");
9/**
10 * Validator class provides a bunch of functions that perform
11 * validations on the request parameters and request body.
12 */
13class Validator {
14 constructor(ctx) {
15 this.ctx = ctx;
16 }
17 /**
18 * The validation executed before type coercion. Like
19 * checking absence.
20 *
21 * @param type - A parameter's type.
22 * @param value - A parameter's raw value from http request.
23 * @param opts - options
24 */
25 validateParamBeforeCoercion(value, opts) {
26 if (this.isAbsent(value) && this.isRequired(opts)) {
27 const name = this.ctx.parameterSpec.name;
28 throw __1.RestHttpErrors.missingRequired(name);
29 }
30 }
31 /**
32 * Check is a parameter required or not.
33 *
34 * @param opts
35 */
36 isRequired(opts) {
37 if (this.ctx.parameterSpec.required)
38 return true;
39 if (opts === null || opts === void 0 ? void 0 : opts.required)
40 return true;
41 return false;
42 }
43 /**
44 * Return `true` if the value is empty, return `false` otherwise.
45 *
46 * @param value
47 */
48 // eslint-disable-next-line @typescript-eslint/no-explicit-any
49 isAbsent(value) {
50 var _a;
51 if (value === '' || value === undefined)
52 return true;
53 const spec = this.ctx.parameterSpec;
54 const schema = (_a = this.ctx.parameterSpec.schema) !== null && _a !== void 0 ? _a : {};
55 const valueIsNull = value === 'null' || value === null;
56 if (this.isUrlEncodedJsonParam()) {
57 // is this an url encoded Json object query parameter?
58 // check for NULL values
59 if (valueIsNull)
60 return true;
61 }
62 else if (spec.schema) {
63 // if parameter spec contains schema object, check if supplied value is NULL
64 if (schema.type === 'object' && valueIsNull)
65 return true;
66 }
67 return false;
68 }
69 /**
70 * Return `true` if defined specification is for a url encoded Json object query parameter
71 *
72 * for url encoded Json object query parameters,
73 * schema is defined under content['application/json']
74 */
75 isUrlEncodedJsonParam() {
76 var _a, _b;
77 const spec = this.ctx.parameterSpec;
78 if (spec.in === 'query' && ((_b = (_a = spec.content) === null || _a === void 0 ? void 0 : _a['application/json']) === null || _b === void 0 ? void 0 : _b.schema)) {
79 return true;
80 }
81 return false;
82 }
83}
84exports.Validator = Validator;
85//# sourceMappingURL=validator.js.map
\No newline at end of file