@nestjs/common
Version:
Nest - modern, fast, powerful node.js web framework (@common)
55 lines (54 loc) • 2.04 kB
JavaScript
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 = Object.assign(isArray ? [] : Object.create(Object.getPrototypeOf(value)), value);
copies.set(value, copy);
for (const key of Reflect.ownKeys(copy)) {
copy[key] = this.copyDefaultValue(copy[key], copies);
}
return copy;
}
};
DefaultValuePipe = __decorate([
Injectable(),
__metadata("design:paramtypes", [Object])
], DefaultValuePipe);
export { DefaultValuePipe };