UNPKG

2.54 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.ParseBoolPipe = void 0;
4const tslib_1 = require("tslib");
5const injectable_decorator_1 = require("../decorators/core/injectable.decorator");
6const optional_decorator_1 = require("../decorators/core/optional.decorator");
7const http_status_enum_1 = require("../enums/http-status.enum");
8const http_error_by_code_util_1 = require("../utils/http-error-by-code.util");
9const shared_utils_1 = require("../utils/shared.utils");
10/**
11 * Defines the built-in ParseBool Pipe
12 *
13 * @see [Built-in Pipes](https://docs.nestjs.com/pipes#built-in-pipes)
14 *
15 * @publicApi
16 */
17let ParseBoolPipe = class ParseBoolPipe {
18 constructor(options) {
19 this.options = options;
20 options = options || {};
21 const { exceptionFactory, errorHttpStatusCode = http_status_enum_1.HttpStatus.BAD_REQUEST } = options;
22 this.exceptionFactory =
23 exceptionFactory ||
24 (error => new http_error_by_code_util_1.HttpErrorByCode[errorHttpStatusCode](error));
25 }
26 /**
27 * Method that accesses and performs optional transformation on argument for
28 * in-flight requests.
29 *
30 * @param value currently processed route argument
31 * @param metadata contains metadata about the currently processed route argument
32 */
33 async transform(value, metadata) {
34 if ((0, shared_utils_1.isNil)(value) && this.options?.optional) {
35 return value;
36 }
37 if (this.isTrue(value)) {
38 return true;
39 }
40 if (this.isFalse(value)) {
41 return false;
42 }
43 throw this.exceptionFactory('Validation failed (boolean string is expected)');
44 }
45 /**
46 * @param value currently processed route argument
47 * @returns `true` if `value` is said 'true', ie., if it is equal to the boolean
48 * `true` or the string `"true"`
49 */
50 isTrue(value) {
51 return value === true || value === 'true';
52 }
53 /**
54 * @param value currently processed route argument
55 * @returns `true` if `value` is said 'false', ie., if it is equal to the boolean
56 * `false` or the string `"false"`
57 */
58 isFalse(value) {
59 return value === false || value === 'false';
60 }
61};
62exports.ParseBoolPipe = ParseBoolPipe;
63exports.ParseBoolPipe = ParseBoolPipe = tslib_1.__decorate([
64 (0, injectable_decorator_1.Injectable)(),
65 tslib_1.__param(0, (0, optional_decorator_1.Optional)()),
66 tslib_1.__metadata("design:paramtypes", [Object])
67], ParseBoolPipe);