UNPKG

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