我设置了一个 Controller 级拦截器@UseInterceptors(CacheInterceptor)
。
现在我希望 Controller 路由之一忽略该拦截器,有没有办法在nest.js中实现这一点?
对于这种特殊情况,我希望能够禁用其中一个路由的 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
}
}
最佳答案
根据this issue ,有no additional exclude decorator但您可以只扩展 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);
}
}
关于javascript - 如何忽略 NestJS 中特定路由的拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54471331/