Nestjs框架中的元数据是什么以及何时使用方法@setmetadata?
我正在从 Nest 文档中学习课程主题反思和元数据。他们使用了 @setmetadata('roles')
但我不知道元数据来自以及何时使用?
I am learning a course topic reflection and metadata from nest documentation. They used @setmetadata('roles')
but I don't know metadata come from and when they are used?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先让我们解释一下元数据的一般含义。
元数据通常是指关于数据的数据。它以更简单的术语对数据进行描述(例如有关图像的数据)。以此处为例。
Nest 提供了通过 @SetMetadata 将自定义数据附加到路由处理程序的功能。它是一种以声明方式定义和存储有关控制器(端点)的数据的方法。
@SetMetadata
存储键值对。例如,这里我设置一个键
IS_PUBLIC_KEY
,并将值设置为true
。在这种情况下,您定义一个名为
role
的键(很可能并且看起来可能缺少一个值),它将定义哪些特定类型或角色可以访问此控制器。当您想要定义守卫时可以使用它。例如,我使用上面的
findAll
控制器作为公共 api。在我的防护实现中,我检查并查看 IsPublic 的值是否为 true,然后允许任何使用者使用该 API。希望这能回答您的问题。
First lets explain what metadata generally means.
Metadata in general means data about data. Its a description of the data in more simpler terms (for e.g data about an image). Taking an example from here.
Nest provides the ability to attach custom data to route handlers through
@SetMetadata
. Its a way to declaratively define and store data about your controller(endpoint).@SetMetadata
stores the key value pairs. For example,Here I am setting a key
IS_PUBLIC_KEY
with a value set totrue
.In this scenario you are defining a key named
role
(most probably and it seems it may be missing a value) which will define what certain types or role can access this controller.You can use it when you want to define the Guards. For instance, I am using the above
findAll
controller as a public api. In my guard implementation, I check and see if the value of IsPublic is true then allow any consumer to consume the API.Hope this answers your question.
https://docs.nestjs.com/fundamentals/execution-context#反射和元数据:
https://docs.nestjs.com/fundamentals/execution-context#reflection-and-metadata: