[Support] 请问如何使用 decorator 实现开放的 api,比如 @Public 作用在路由上,表示该路由无需验证身份 #3880
-
Describe the problem(描述问题) @Inject()
jwtService: JwtService;
@Public()
@Post('/login')
async login(@Body() user: UserOptions, ctx: Context) { Midway Versions(Midway 版本)新手请教:我看到文档中在中间件中使用 ignore 或者 match 通过匹配路由的方式实现的,之前接触过 nestjs 使用装饰器实现,所以我在想 midway 怎么实现呢,下面我写的(可能不对),但是在中间件中怎么获取 isPublic 的布尔值呢? export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => {
return (target: any, propertyKey: string) => {
savePropertyMetadata(IS_PUBLIC_KEY, true, target, propertyKey);
};
}; |
Beta Was this translation helpful? Give feedback.
Answered by
waitingsong
May 31, 2024
Replies: 4 comments 14 replies
-
跟这个同样的诉求...: #3719 |
Beta Was this translation helpful? Give feedback.
2 replies
-
|
Beta Was this translation helpful? Give feedback.
3 replies
-
发现使用守卫可以获取到元数据,但是中间件不行? // role.decorator.ts
export const Roles = (...roles: number[]) => {
return (target: any, propertyKey: string) => {
savePropertyMetadata(ROLES_KEY, roles, target, propertyKey);
};
};
// role.guard.ts
async canActivate(ctx: Context, supplierClz: any, methodName: string) {
// 依赖 supplierClz 和 methodName 能获取到元数据
// 能获取到 @Role(1) 装饰器的值 [1]
const roles = getPropertyMetadata(
ROLES_KEY,
supplierClz,
methodName
); |
Beta Was this translation helpful? Give feedback.
2 replies
-
就是这样吧。。我写过啊。。 |
Beta Was this translation helpful? Give feedback.
7 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
核心是在每个请求时通过
拿到路由信息,然后挂载到
ctx
上面,后面的中间件、组件、装饰器都可以用了。我把获取这个路由信息包装了下,内部有个缓存,可以极大减小相同接口后续请求的延迟:
首次请求(无缓存)vs 后续请求(有缓存)大约是 200:1 的开销。接口越多比例应该越大。