UNPKG

5.82 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.ParseArrayPipe = 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");
10const validation_pipe_1 = require("./validation.pipe");
11const VALIDATION_ERROR_MESSAGE = 'Validation failed (parsable array expected)';
12const DEFAULT_ARRAY_SEPARATOR = ',';
13/**
14 * Defines the built-in ParseArray Pipe
15 *
16 * @see [Built-in Pipes](https://docs.nestjs.com/pipes#built-in-pipes)
17 *
18 * @publicApi
19 */
20let ParseArrayPipe = class ParseArrayPipe {
21 constructor(options = {}) {
22 this.options = options;
23 this.validationPipe = new validation_pipe_1.ValidationPipe(Object.assign({ transform: true, validateCustomDecorators: true }, options));
24 const { exceptionFactory, errorHttpStatusCode = http_status_enum_1.HttpStatus.BAD_REQUEST } = options;
25 this.exceptionFactory =
26 exceptionFactory ||
27 (error => new http_error_by_code_util_1.HttpErrorByCode[errorHttpStatusCode](error));
28 }
29 /**
30 * Method that accesses and performs optional transformation on argument for
31 * in-flight requests.
32 *
33 * @param value currently processed route argument
34 * @param metadata contains metadata about the currently processed route argument
35 */
36 async transform(value, metadata) {
37 if (!value && !this.options.optional) {
38 throw this.exceptionFactory(VALIDATION_ERROR_MESSAGE);
39 }
40 else if ((0, shared_utils_1.isNil)(value) && this.options.optional) {
41 return value;
42 }
43 if (!Array.isArray(value)) {
44 if (!(0, shared_utils_1.isString)(value)) {
45 throw this.exceptionFactory(VALIDATION_ERROR_MESSAGE);
46 }
47 else {
48 try {
49 value = value
50 .trim()
51 .split(this.options.separator || DEFAULT_ARRAY_SEPARATOR);
52 }
53 catch (_a) {
54 throw this.exceptionFactory(VALIDATION_ERROR_MESSAGE);
55 }
56 }
57 }
58 if (this.options.items) {
59 const validationMetadata = {
60 metatype: this.options.items,
61 type: 'query',
62 };
63 const isExpectedTypePrimitive = this.isExpectedTypePrimitive();
64 const toClassInstance = (item, index) => {
65 try {
66 item = JSON.parse(item);
67 }
68 catch (_a) { }
69 if (isExpectedTypePrimitive) {
70 return this.validatePrimitive(item, index);
71 }
72 return this.validationPipe.transform(item, validationMetadata);
73 };
74 if (this.options.stopAtFirstError === false) {
75 // strict compare to "false" to make sure
76 // that this option is disabled by default
77 let errors = [];
78 const targetArray = value;
79 for (let i = 0; i < targetArray.length; i++) {
80 try {
81 targetArray[i] = await toClassInstance(targetArray[i]);
82 }
83 catch (err) {
84 let message;
85 if (err.getResponse) {
86 const response = err.getResponse();
87 if (Array.isArray(response.message)) {
88 message = response.message.map((item) => `[${i}] ${item}`);
89 }
90 else {
91 message = `[${i}] ${response.message}`;
92 }
93 }
94 else {
95 message = err;
96 }
97 errors = errors.concat(message);
98 }
99 }
100 if (errors.length > 0) {
101 throw this.exceptionFactory(errors);
102 }
103 return targetArray;
104 }
105 else {
106 value = await Promise.all(value.map(toClassInstance));
107 }
108 }
109 return value;
110 }
111 isExpectedTypePrimitive() {
112 return [Boolean, Number, String].includes(this.options.items);
113 }
114 validatePrimitive(originalValue, index) {
115 if (this.options.items === Number) {
116 const value = originalValue !== null && originalValue !== '' ? +originalValue : NaN;
117 if (isNaN(value)) {
118 throw this.exceptionFactory(`${(0, shared_utils_1.isUndefined)(index) ? '' : `[${index}] `}item must be a number`);
119 }
120 return value;
121 }
122 else if (this.options.items === String) {
123 if (!(0, shared_utils_1.isString)(originalValue)) {
124 return `${originalValue}`;
125 }
126 }
127 else if (this.options.items === Boolean) {
128 if (typeof originalValue !== 'boolean') {
129 throw this.exceptionFactory(`${(0, shared_utils_1.isUndefined)(index) ? '' : `[${index}] `}item must be a boolean value`);
130 }
131 }
132 return originalValue;
133 }
134};
135ParseArrayPipe = tslib_1.__decorate([
136 (0, injectable_decorator_1.Injectable)(),
137 tslib_1.__param(0, (0, optional_decorator_1.Optional)()),
138 tslib_1.__metadata("design:paramtypes", [Object])
139], ParseArrayPipe);
140exports.ParseArrayPipe = ParseArrayPipe;