Custom Middleware — Series 3

Preview — 3 of 10 questions

What does exclude() do here, and what is the common mistake?

javascript
consumer
  .apply(AuthMiddleware)
  .exclude({ path: 'auth/(.*)', method: RequestMethod.ALL })
  .forRoutes('*');
AIt removes the excluded routes from the application entirely
BIt applies the middleware only to the excluded paths, inverting forRoutes
CIt excludes the paths from every middleware registered in this module
DIt carves the auth subtree out of this middleware's coverage; the usual mistake is assuming the pattern is matched against the raw URL — it is matched against the registered route path, so a global prefix or a mismatched wildcard syntax silently leaves the routes covered after all

When does the middleware run?

javascript
consumer.apply(MetricsMiddleware).forRoutes({ path: 'reports', method: RequestMethod.GET });
// no controller declares GET /reports
AOn every request, since an unmatched path falls through to all middleware
BNever for requests to /reports: middleware is mounted on the path, but a request only reaches it through the router, and with no route registered the request is answered with a 404 by the adapter — so middleware bound to a non-existent route is silently dead code
COnce at startup, to validate the path
DOn /reports requests only, returning 404 afterwards

Is normalising the body here a good idea?

javascript
use(req: Request, res: Response, next: NextFunction) {
  if (typeof req.body?.email === 'string') req.body.email = req.body.email.trim().toLowerCase();
  next();
}
AIt works — the body is already parsed and @Body() reads the same object — but it hides a transformation from everyone reading the DTO, and it runs for every route the middleware covers whether or not the field is meaningful there; @Transform() on the DTO expresses the same rule where the shape is declared
BIt has no effect, because @Body() reads from a copy of the request
CIt throws, since the parsed body is frozen
DIt works and is preferred, since middleware runs before validation

Sign up free to play

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