Guards & Interceptors
In the GraphQL world, a lot of articles complain how to handle stuff like an authentication, or side-effects of operations. Should we put it inside the business logic? Shall we use a higher-order function to enhance queries and mutations as well for example with authorization logic? There's no single answer.
The Nest ecosystem is trying to help with this issue using existing features like guards and interceptors. The idea behind them is to reduce redundancy and also, create a well-structured applications.
Usage
You can use both guards and interceptors in the same way as in the simple REST application.
They act equivalently until the request is passed as a rootValue in the graphqlExpress middleware.
Let's have a look at the following code:
@Query('author')
@UseGuards(AuthGuard)
async getAuthor(obj, args, context, info) {
const { id } = args;
return await this.authorsService.findOneById(id);
}
Thanks to that you can move your authentication logic to the guard, or even reuse the same guard class as in the REST application. The interceptors works in the exact same way:
@Mutation()
@UseInterceptors(EventsInterceptor)
async upvotePost(_, { postId }) {
return await this.postsService.upvoteById({ id: postId });
}
Write once, use everywhere :)