All quizzesMedium
Custom Pipeline Elements — Series 2
Preview — 3 of 10 questions
What does mixin() contribute here?
javascript
export const RoleGuard = (role: string): Type<CanActivate> => {
@Injectable()
class RoleGuardMixin implements CanActivate {
constructor(private readonly users: UsersService) {}
async canActivate(context: ExecutionContext) {
const { user } = context.switchToHttp().getRequest();
return this.users.hasRole(user.id, role);
}
}
return mixin(RoleGuardMixin);
};
@UseGuards(RoleGuard('admin'))
@Get('panel') panel() {}AIt caches the guard instance so the same object is reused across every role
BIt converts the class into a functional guard, removing the need for @Injectable()
CIt merges the generated class with the global guard list
DIt registers the dynamically created class with Nest's injector so the returned type can be resolved through DI — meaning UsersService is injected normally, even though the class was defined inside a function
What must be passed to the parameter decorator?
javascript
@Injectable()
export class SlugExistsPipe implements PipeTransform {
constructor(private readonly catsService: CatsService) {}
async transform(slug: string) {
if (!(await this.catsService.existsBySlug(slug))) throw new NotFoundException();
return slug;
}
}
@Get(':slug')
findOne(@Param('slug', ???) slug: string) {}Anew SlugExistsPipe(), supplying the dependency manually
BThe class reference, SlugExistsPipe — passing the class lets Nest instantiate it through the container so CatsService is injected; passing an instance would bypass DI entirely
CNothing; pipes with dependencies must be registered globally
DA factory function returning the pipe
What is the consequence of returning of(hit)?
javascript
@Injectable()
export class CacheInterceptor implements NestInterceptor {
async intercept(context: ExecutionContext, next: CallHandler) {
const key = this.keyFor(context);
const hit = await this.cache.get(key);
if (hit) return of(hit);
return next.handle().pipe(tap(value => this.cache.set(key, value)));
}
}AThe handler still executes, but its result is discarded in favour of the cached value
BNest throws, because next.handle() must be called exactly once in every interceptor
CThe route handler is never invoked — next.handle() is what triggers it, so skipping the call means the cached value becomes the response and no pipes or handler logic run
DThe cached value is merged with the handler's result
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.