As I work on my personal project in NestJS for educational purposes, integrating Swagger has become a key focus. I want to showcase that a specific route could potentially result in an UnauthorizedException
response. To achieve this, I need to add the following code snippet:
@ApiUnauthorizedResponse({ description: 'Unauthorized' })
@Get()
findAll() {
return this.usersService.findAll();
}
However, I aim to streamline this process by applying the decorator to all non-public routes. My approach involves creating an interceptor that analyzes the current route handler and its metadata on whether it is public or not. If it's not public, then the decorator should be added dynamically to the handler reference. But how can this be achieved effectively?
The envisioned interceptor concept is showcased below, albeit with temporary naming:
@Injectable()
export class UnauthSwaggerInterceptor implements NestInterceptor {
constructor(private readonly reflector: Reflector) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const handler = context.getHandler();
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC, [
context.getHandler(),
context.getClass(),
]);
if (!isPublic) {
// Apply Swagger decorator to handler
}
return next.handle();
}
}
This plan involves first identifying the current handler, followed by extracting the isPublic
metadata from the route using a reflector
. Subsequently, verifying if the route is indeed not public to apply the necessary decorator. Routes marked as public are designated with the public decorator.
export const IS_PUBLIC = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC, true);
Ultimately, the objective is to append the aforementioned Unauthorized response decorator to these specific non-public handlers. Is such a task feasible? Since it involves runtime references rather than function declarations, the correct course of action remains uncertain.
There exists ambiguity on directly applying the decorator to the function itself, especially since decorators typically pertain to classes but in this scenario, they should only affect controller methods. The Nest Swagger plugin seemingly accomplishes similar functionality by dynamically adding decorators based on predefined rules. This desired outcome aligns with my own objectives, assuming it can be realized.