ngATL Conference Atlanta, GA

NestJS on 2018 ngATL Conference Atlanta, GA

NestJS 2018 ngATL

LEARN MORE

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:

JavaScript TypeScript
TypeScript

@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:

JavaScript TypeScript
TypeScript

@Mutation()
@UseInterceptors(EventsInterceptor)
async upvotePost(_, { postId }) {
  return await this.postsService.upvoteById({ id: postId });
}

Write once, use everywhere :)

Sponsors

Nest is an MIT-licensed open source project. It can grow thanks to the support by these awesome people. If you'd like to join them, please read more here. Thanks!

Become a sponsor