Execution Order & Scopes — Series 2

Preview — 3 of 10 questions

In what order do the three run on the way in?

javascript
// AppModule
{ provide: APP_INTERCEPTOR, useClass: GlobalInterceptor }

@UseInterceptors(ControllerInterceptor)
@Controller('cats')
export class CatsController {
  @UseInterceptors(RouteInterceptor)
  @Get() findAll() {}
}
ARoute, controller, global — the most specific binding is the outermost layer
BGlobal, controller, route — enhancers are applied from the broadest scope inward, so the global one wraps everything and the route-level one sits closest to the handler
CThe order is unspecified when bindings come from different levels
DOnly the route-level interceptor runs; the narrower binding overrides the others

On a cache hit, is the body still validated?

javascript
@Injectable()
export class CacheInterceptor implements NestInterceptor {
  async intercept(ctx: ExecutionContext, next: CallHandler) {
    const hit = await this.cache.get(this.keyFor(ctx));
    return hit ? of(hit) : next.handle();
  }
}

@UseInterceptors(CacheInterceptor)
@Post()
create(@Body() dto: CreateCatDto) {}   // global ValidationPipe is registered
AYes — pipes run immediately after guards, before any interceptor is entered
BYes, but only the global pipes; parameter-level pipes are skipped
CNo, and the handler runs anyway with unvalidated arguments
DNo — argument binding (and therefore the pipe chain) is part of what next.handle() triggers, so skipping the call skips both validation and the handler

What is the practical difference between the two outcomes?

javascript
async canActivate(ctx: ExecutionContext) {
  const user = ctx.switchToHttp().getRequest().user;
  if (!user) throw new UnauthorizedException('Token missing or expired'); // (1)
  return user.roles.includes('admin');                                     // (2)
}
APath (1) produces a 401 with your own message, while path (2) returning false produces Nest's generic 403 Forbidden — so throwing is how a guard distinguishes "not authenticated" from "not allowed"
BBoth produce 403; the thrown message is discarded
CPath (1) bypasses exception filters, while path (2) goes through them
DReturning false is deprecated in favour of throwing

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.