import { Component } from '@celljs/core'; import { ArgumentMetadata, PipeTransform } from './pipe-protocol'; const TYPES: Function[] = [String, Number, Boolean, Date]; /** * Converts request data to a `String`, `Number`, `Boolean` or `Date` parameter as class-transformer did: * `'5'` → `5`, `'abc'` → `NaN`, `'false'` → `true` (any non-empty string), arrays item by item; * `null` and `undefined` stay. Parameters of other types get the data as it is; `@celljs/validation` * turns it into instances of the parameter class and validates them. */ @Component(PipeTransform) export class TypeConversionPipe implements PipeTransform { readonly priority = 1000; transform(value: any, { argType }: ArgumentMetadata): any { if (!argType || !TYPES.includes(argType) || (value !== null && typeof value === 'object' && !Array.isArray(value))) { return value; } return this.convert(argType, value); } protected convert(type: Function, value: unknown): unknown { if (value === null || value === undefined) { return value; } if (Array.isArray(value)) { return value.map(item => this.convert(type, item)); } if (type === Date) { return value instanceof Date ? value : new Date(value as string); } return (type as (value: unknown) => unknown)(value); } }