我想到达UserEntity类,它是使用HashedRouteParam装饰器从PostsController的装饰器发送的。下面是我当前的代码示例:
自定义控制器装饰器:
import { ControllerOptions as NestControllerOptions } from '@nestjs/common/decorators/core/controller.decorator';
import { Controller as NestController } from '@nestjs/common';
import { Entity } from '../../config/mikro-orm.config';
import { BaseEntity } from '../../database/entities';
export const ENTITY_KEY = Symbol('entity');
interface ControllerOptions extends NestControllerOptions {
entity?: Entity;
}
type ControllerParams = ControllerOptions | string | string[] | Entity;
export function Controller<TFunction extends Function>(
prefixOrOptionsOrEntity?: ControllerParams,
): ClassDecorator {
if (
typeof prefixOrOptionsOrEntity === 'undefined' ||
typeof prefixOrOptionsOrEntity === 'string' ||
Array.isArray(prefixOrOptionsOrEntity)
) {
return NestController(prefixOrOptionsOrEntity);
}
let entity: Entity;
if ((prefixOrOptionsOrEntity as Entity).prototype instanceof BaseEntity) {
entity = prefixOrOptionsOrEntity as Entity;
} else if ((prefixOrOptionsOrEntity as ControllerOptions).entity) {
entity = (prefixOrOptionsOrEntity as ControllerOptions).entity;
delete (prefixOrOptionsOrEntity as ControllerOptions).entity;
}
return ((target: TFunction) => {
Reflect.defineMetadata(ENTITY_KEY, entity, target.constructor);
return NestController(prefixOrOptionsOrEntity as any)(target);
}) as any;
}
PostsController:
import { Controller } from '../common/decorators';
@Controller(PostEntity)
export class PostsController {
...
@Get(':id')
async findOne(@HashedRouteParam('id') id: number) {
...
}
}
HashedRouteParam装饰器:
export function HashedRouteParam(
payload: IHashedRoutePayload,
...pipes: (Type<PipeTransform> | PipeTransform)[]
) {
return (
target: Object,
propertyKey: string | symbol,
parameterIndex: number,
) => {
const entity = Reflect.getMetadata(ENTITY_KEY, target.constructor);
...
const extendedPipes = [decodePipe, ...pipes];
return Param(property, ...extendedPipes)(
target,
propertyKey,
parameterIndex,
);
};
}
不管用
Controller Decorator函数上的实体对象未将未定义的实体定义为元数据。没事我已经记录下来了
但是当我尝试在HashedRouteParam装饰器上获取元数据时,实体似乎未定义。
我做错了什么,有其他解决方案吗?我想在我的控制器上指定实体类型,以便以后在特定情况下使用它们。
如果我在自定义Controller装饰器上使用SetMetadata(来自'@nestjs/common'),我如何从HashedRouteParam装饰器访问它?我不能在HashedRouteParam函数上使用这个.reflector。我可以以某种方式?
1条答案
按热度按时间qnakjoqk1#
你可以尝试“OnModuleInit”接口。使一个类实现OnModuleInit并导入这个类。在实现OnModuleInit的类中,您可以注入提供的示例并在“onModuleInit”方法中使用它。