从Nestjs控制器访问元数据
有没有办法从控制器方法访问元数据?
例如,我将元数据添加到带有装饰器的setMetadata()的控制器类中。
我知道如何在警卫中访问元数据。您需要注入反射器和guard.canactivate()具有exputionContext参数。
canActivate(context: ExecutionContext): boolean {
metadata: SomeType = this.reflector.get<EnabledFeatures>(SOME_METADATA_KEY, [context.getClass()]);
}
要获得元数据,我需要2个组件:反射器和执行context。 我可以将Reflector注入控制器,但是如何从控制器访问ExecutionContext?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设我们使用
@setMetadata
在Controller
上设置了一些元数据:我们可以通过创建我们的自定义参数装饰器:
然后我们可以在控制器的方法上使用它:
一些注释
@setMetadata不是直接的
@setMetadata
的好习惯用法并不是真正的好习惯。更喜欢创建特定的装饰器(用于代码的维护和可读性):
fover.getMetadata api vs喷油器
,即使
Reffled.getMetAdata
is 反射器 Nestjs的API,将来可能会更改。因此,如果我们只想处理Nestjs的公共/记录的API,我们可以:
注入器
,executionContext
获取元数据request request
实例中设置结果。其他自定义参数装饰器将从
请求
中检索数据并将其返回。更复杂,但不使用直接调用
Reflect.getMetadata
api。Assuming we set some metadata on
Controller
with@SetMetadata
:We can have access to it, by creating our custom param decorator:
And then we can use it on controller's method :
Some notes
@SetMetadata not a good practice
Usage of
@SetMetadata
directly is not really a good practice. Prefer to create a specific decorator (for maintenance and readability of code) :Reflect.getMetadata API vs Injector
Even if
Reflect.getMetadata
is in fact called byReflector
API of NestJS, it could be changed in the future.So if we want to deal with only public/documented API of NestJS, we can:
Injector
,ExecutionContext
Request
instance.An other custom param decorator will retrieve data from
Request
and return it.More complicated, but without using direct call to
Reflect.getMetadata
API.