Pipeline Internals

Preview — 3 of 10 questions

Internally, which NestJS construct assembles guards, interceptors, pipes, and the handler into a single callable per route at bootstrap?

javascript
// Conceptually, per route Nest produces something like:
// async (req, res, next) => {
//   await runGuards(ctx);
//   return runInterceptors(ctx, () => runPipes(ctx).then(args => handler(...args)));
// }
AThe RouterExecutionContext (route handler factory) built by the core's execution context creators
BThe RouterModule
CThe Reflector
DThe HttpAdapterHost

A guard must read metadata that could be on the class or the method, preferring the method. Which call expresses this precisely?

javascript
import { SetMetadata, CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

export const Public = () => SetMetadata('isPublic', true);

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}
  canActivate(ctx: ExecutionContext): boolean {
    const isPublic = this.reflector.getAllAndOverride<boolean>('isPublic', [
      ctx.getHandler(),
      ctx.getClass(),
    ]);
    return isPublic === true ? true : Boolean(ctx.switchToHttp().getRequest().user);
  }
}
Areflector.get(KEY, context.getClass())
Breflector.getAllAndOverride(KEY, [context.getHandler(), context.getClass()])
CReflect.getMetadata(KEY, context.getArgs())
Dreflector.getAllAndMerge(KEY, [context.getClass(), context.getHandler()])

A single interceptor serves HTTP, WebSocket, and gRPC. What is the type of context.getType() and how should you safely extend it?

javascript
import { ExecutionContext, Injectable, NestInterceptor, CallHandler } from '@nestjs/common';
import { GqlContextType } from '@nestjs/graphql';
import { Observable } from 'rxjs';

@Injectable()
export class MultiInterceptor implements NestInterceptor {
  intercept(ctx: ExecutionContext, next: CallHandler): Observable<unknown> {
    const type = ctx.getType<GqlContextType>(); // 'http' | 'ws' | 'rpc' | 'graphql'
    return next.handle();
  }
}
A'http' | 'ws' | 'rpc' by default, extendable via a generic like getType<GqlContextType>()
BAlways string; no generic support
Cnumber representing a transport enum
D'rest' | 'graphql' only

Sign up free to play

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