All quizzesMedium
Custom Middleware — Series 2
Preview — 3 of 10 questions
What does the class form offer that the functional form does not?
javascript
// (1)
export function logger(req: Request, res: Response, next: NextFunction) { next(); }
// (2)
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
constructor(private readonly config: ConfigService) {}
use(req: Request, res: Response, next: NextFunction) { next(); }
}AThe ability to terminate the request without calling next()
BAccess to the route's handler metadata through Reflector
CAutomatic error handling for thrown exceptions
DDependency injection — a class registered in configure() is instantiated by the container, so it can inject services; a plain function is called as-is with no container involvement
Why is the raw body needed here rather than the parsed one?
javascript
const app = await NestFactory.create(AppModule, { rawBody: true });
@Post('webhook')
handle(@Req() req: RawBodyRequest<Request>, @Headers('stripe-signature') sig: string) {
const event = this.stripe.webhooks.constructEvent(req.rawBody!, sig, secret);
}ABecause JSON parsing is too slow for high-volume webhook traffic
BBecause the signature is an HMAC over the exact bytes that were sent; re-serialising the parsed object can change key order, spacing or number formatting, producing a different digest and a failed verification
CBecause webhook payloads are not valid JSON
DBecause @Body() is unavailable on POST routes that declare @Headers()
What does passing a controller class to forRoutes() mean?
javascript
configure(consumer: MiddlewareConsumer) {
consumer.apply(TenantMiddleware).forRoutes(CatsController);
}AThe middleware applies to every route declared by that controller, including any added later — which keeps the configuration correct as the controller grows
BThe middleware is injected into the controller as a provider
COnly the controller's first route is covered
DThe controller is excluded from the middleware, which is the inverse of exclude()
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.