[英]How to ignore an interceptor for a particular route in NestJS
I have set a controller level interceptor @UseInterceptors(CacheInterceptor)
.我已经设置了一个控制器级拦截器
@UseInterceptors(CacheInterceptor)
。 Now I want one of the controller routes to ignore that interceptor, is there any way to achieve that in nest.js?现在我希望控制器路由之一忽略该拦截器,有没有办法在 nest.js 中实现这一点?
For this particular case I want to be able to disable CacheInterceptor
for one of the routes.对于这种特殊情况,我希望能够为其中一个路由禁用
CacheInterceptor
。
@Controller()
@UseInterceptors(CacheInterceptor)
export class AppController {
@Get('route1')
route1() {
return ...;
}
@Get('route2')
route2() {
return ...;
}
@Get('route3')
route3() {
return ...;
}
@Get('route4')
route4() {
return ...; // do not want to cache this route
}
}
According to this issue , there is no additional exclude decorator but instead you can just extend the CacheInterceptor
and provide the excluded routes. 根据此问题 , 没有其他的排除装饰器 ,而是可以扩展
CacheInterceptor
并提供排除的路由。
@Injectable()
class HttpCacheInterceptor extends CacheInterceptor {
trackBy(context: ExecutionContext): string | undefined {
const request = context.switchToHttp().getRequest();
const isGetRequest = this.httpServer.getRequestMethod(request) === 'GET';
const excludePaths = ['path1', 'path2'];
^^^^^^^^^^^^
if (
!isGetRequest ||
(isGetRequest && excludePaths.includes(this.httpServer.getRequestUrl))
) {
return undefined;
}
return this.httpServer.getRequestUrl(request);
}
}
const IgnoredPropertyName = Symbol('IgnoredPropertyName')
export function CustomInterceptorIgnore() {
return function(target, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.value[IgnoredPropertyName] = true
};
}
@Injectable()
export class CustomInterceptor implements NestInterceptor {
constructor() {}
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
const request: ExtendedUserRequest = context.switchToHttp().getRequest()
const isIgnored = context.getHandler()[IgnoredPropertyName]
if (isIgnored) {
return next.handle()
}
}
}
@Patch('route')
@CustomInterceptorIgnore()
async someHandle () {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.