Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 1x 1x 1x 1x 1x | import { BadRequestException, CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validateSync } from 'class-validator';
import { EVENT_SDK_CONTEXT_TYPE } from './shared/shared.const';
@Injectable()
export class EventSdkGuard implements CanActivate {
canActivate(context: ExecutionContext) {
const ctxType = context.getType<string>();
Iif (ctxType !== EVENT_SDK_CONTEXT_TYPE) return true;
const handler = context.getHandler();
const target = context.getClass();
const paramTypes = Reflect.getMetadata('design:paramtypes', target.prototype, handler.name);
const dtoClass = paramTypes?.[0];
// Skip if it's a primitive or no class found
Iif (!dtoClass || [String, Number, Boolean, Object, Array].includes(dtoClass)) return true;
const [data] = context.getArgs<[any, any]>();
const dtoObject: any =
typeof data === 'object'
? plainToInstance(dtoClass, data, { excludeExtraneousValues: true })
: {};
const errors = validateSync(dtoObject, { target: true, value: true });
Iif (errors.length) {
throw new BadRequestException({ errors });
}
return true;
}
}
|