UNPKG

@nestjs/common

Version:

Decorators, pipes, exceptions and utilities for NestJS applications: @Controller(), @Injectable(), @Body(), ValidationPipe, HttpException and more.

65 lines (64 loc) • 2.35 kB
import { __decorate, __metadata } from "tslib"; import { Injectable } from '../decorators/core/injectable.decorator.js'; import { isNil, isNumber, isPlainObject } from '../utils/shared.utils.js'; /** * Defines the built-in DefaultValue Pipe * * A default value that is an array or a plain object is copied on every call * (along with the arrays and plain objects nested in it), so that a handler * that mutates its argument does not change it for subsequent requests. Any * other object (e.g., a class instance, a `Date` or a `Map`) is returned as is. * * @see [Built-in Pipes](https://docs.nestjs.com/pipes#built-in-pipes) * * @publicApi */ let DefaultValuePipe = class DefaultValuePipe { defaultValue; constructor(defaultValue) { this.defaultValue = defaultValue; } transform(value, _metadata) { if (isNil(value) || (isNumber(value) && isNaN(value))) { return this.copyDefaultValue(this.defaultValue); } return value; } /** * Copies `value` if it is an array or a plain object, along with the arrays * and plain objects nested in it. `copies` maps the objects copied so far * to their copies, so that shared and circular references are preserved. */ copyDefaultValue(value, copies) { const isArray = Array.isArray(value) && Object.getPrototypeOf(value) === Array.prototype; if (!isArray && !isPlainObject(value)) { return value; } copies ??= new Map(); if (copies.has(value)) { return copies.get(value); } const copy = isArray ? new Array(value.length) : Object.create(Object.getPrototypeOf(value)); copies.set(value, copy); for (const key of Reflect.ownKeys(value)) { if (!Object.prototype.propertyIsEnumerable.call(value, key)) { continue; } Object.defineProperty(copy, key, { value: this.copyDefaultValue(Reflect.get(value, key), copies), enumerable: true, configurable: true, writable: true, }); } return copy; } }; DefaultValuePipe = __decorate([ Injectable(), __metadata("design:paramtypes", [Object]) ], DefaultValuePipe); export { DefaultValuePipe };