我正在尝试将提供程序注入包装在装饰器中的防护中,但是Nest无法解决依赖关系,这给我带来了下一个错误:
[ExceptionHandler] Nest can't resolve dependencies of the SecuredGuard (Reflector, ?). Please make sure that the argument at index [1] is available in the SecuredGuard context.
我的方法的主要目的是避免像这样使用两个单独的装饰器:
@Controller()
export class AppController {
@Get()
@Secured('admin')
@UseGuards(SecuredGuard)
getHello(): string {
return this.appService.getHello();
}
}
然后将@UseGuards(SecuredGuard)
插入我的自定义装饰器@Secured('admin')
内,这样最终会这样:
@Controller()
export class AppController {
@Get()
@Secured('admin')
getHello(): string {
return this.appService.getHello();
}
}
这是我实现自定义装饰器的方式:
export function Secured(...roles: string[]){
const setMetadata = ReflectMetadata('roles', roles)
const setupGuard = UseGuards(SecuredGuard)
return (target: any, key?: string, descriptor?: any) => {
setMetadata(target, key, descriptor);
setupGuard(target, key, descriptor);
}
}
这是我的SecuredGuard
,AuthService
是无法解决的依赖项:
@Injectable()
export class SecuredGuard implements CanActivate {
constructor(
private readonly _reflector: Reflector,
private readonly _authService: AuthService
) { }
async canActivate(context: ExecutionContext): Promise<boolean> {...}
}
secured.guard.ts
和secured.decorator.ts
都是secured.module.ts
的一部分
@Module({
imports: [
SecuredGuard,
AuthModule
],
exports: [
SecuredGuard
],
providers: [
AuthService
]
})
export class SecuredModule {}
正在使用从AuthService
导出的auth.module.ts
@Module({
controllers: [
AuthController
],
providers: [
AuthService
],
imports: [
EmailModule
],
exports: [
AuthService
]
})
export class AuthModule { }
secured.module.ts
正在导入app.module.ts
@Module({
imports: [
SecuredModule
],
controllers: [
AppController
],
providers: [
AppService
],
})
export class AppModule { }
我不知道我是否正在使用适当的方法,或者即使我有可能尝试做任何事情,任何线索也将不胜感激!
答案 0 :(得分:0)