NestJS - 向管道添加其他元数据



有没有办法将其他元数据添加到 NestJS 管道?

元数据属性具有以下值:

export interface ArgumentMetadata {
type: 'body' | 'query' | 'param' | 'custom';
metatype?: Type<any>;
data?: string;
}

请参阅:https://docs.nestjs.com/pipes

我能够通过自定义参数装饰器和自定义管道添加其他元数据。

import { createParamDecorator} from '@nestjs/common'
export const ExtractIdFromBody = createParamDecorator(
(
{
property,
entityLookupProperty = 'id'
}: {
property: string
entityLookupProperty?: string
},
req
) => {
const value = get(req.body, property)
return {
value,
entityLookupProperty // the extra property
}
}
)

然后我使用了这样的装饰器:

@Post()
@UsePipes(new ValidationPipe({ transform: true }))
async doThing(
@ExtractIdFromBody({ property: 'userId', entityLookupProperty: 'someProperty'  }, GetEntityOr404Pipe) entity: Entity,
): Promise<Entity[]> {
return await this.Service.doThing(entity)
}

最新更新