|
| 1 | +import { BadRequestException, Inject, PipeTransform } from '@nestjs/common'; |
| 2 | +import { Repository } from 'typeorm'; |
| 3 | +import AjvCall, { ValidateFunction } from 'ajv'; |
| 4 | + |
| 5 | +import { getEntityName } from '../../../helper'; |
| 6 | +import { |
| 7 | + Entity, |
| 8 | + PipeMixin, |
| 9 | + QuerySchemaTypes, |
| 10 | + ValidationError, |
| 11 | +} from '../../../types'; |
| 12 | +import { isNumberString, isUUID } from 'class-validator'; |
| 13 | + |
| 14 | +export class IdSchemaPipe implements PipeTransform { |
| 15 | + protected validateFunction: ValidateFunction<QuerySchemaTypes>; |
| 16 | + static inject(pip: PipeMixin): void { |
| 17 | + Inject(AjvCall)(pip, 'ajvCall', 1); |
| 18 | + } |
| 19 | + |
| 20 | + constructor( |
| 21 | + protected repository: Repository<Entity>, |
| 22 | + protected ajvCall: AjvCall |
| 23 | + ) { |
| 24 | + const schemaName = getEntityName(this.repository.target); |
| 25 | + this.validateFunction = this.ajvCall.getSchema( |
| 26 | + `inputQuerySchema-${schemaName}` |
| 27 | + ); |
| 28 | + } |
| 29 | + |
| 30 | + async transform(value: unknown): Promise<QuerySchemaTypes> { |
| 31 | + const resource = getEntityName(this.repository.target); |
| 32 | + const columns = this.repository.metadata.columns; |
| 33 | + |
| 34 | + for (const column of columns) { |
| 35 | + if (column.propertyName === 'id') { |
| 36 | + const isUuuidColumn = column.generationStrategy === 'uuid'; |
| 37 | + |
| 38 | + const valid = isUuuidColumn ? isUUID(value) : isNumberString(value); |
| 39 | + |
| 40 | + if (!valid) { |
| 41 | + const message = isUuuidColumn |
| 42 | + ? `Id of resource ${resource} should be uuid` |
| 43 | + : `Id of resource ${resource} should be numeric string`; |
| 44 | + throw new BadRequestException(message); |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return value as QuerySchemaTypes; |
| 50 | + } |
| 51 | +} |
0 commit comments