0
0
NestJSframework~5 mins

Resolvers in NestJS

Choose your learning style9 modes available
Introduction

Resolvers help your app answer questions from users by connecting requests to the right data or actions.

When you want to handle GraphQL queries and mutations in your NestJS app.
When you need to fetch or change data based on user requests.
When you want to organize how your app responds to different GraphQL operations.
When you want to keep your code clean by separating data fetching logic.
When building APIs that use GraphQL to communicate with clients.
Syntax
NestJS
import { Resolver, Query, Mutation, Args } from '@nestjs/graphql';

@Resolver()
export class ExampleResolver {
  @Query(() => String)
  sayHello(): string {
    return 'Hello!';
  }

  @Mutation(() => Boolean)
  updateData(@Args('input') input: string): boolean {
    // update logic here
    return true;
  }
}

@Resolver marks the class as a GraphQL resolver.

@Query and @Mutation decorate methods to handle GraphQL queries and mutations.

Examples
This resolver answers a simple query that returns a greeting string.
NestJS
import { Resolver, Query } from '@nestjs/graphql';

@Resolver()
export class SimpleResolver {
  @Query(() => String)
  greet() {
    return 'Hi there!';
  }
}
This resolver handles a mutation that changes a status and returns true if successful.
NestJS
import { Resolver, Mutation, Args } from '@nestjs/graphql';

@Resolver()
export class UpdateResolver {
  @Mutation(() => Boolean)
  changeStatus(@Args('status') status: string) {
    // pretend to update status
    return true;
  }
}
Sample Program

This resolver stores a message string. You can get the current message with a query, or change it with a mutation.

NestJS
import { Resolver, Query, Mutation, Args } from '@nestjs/graphql';

@Resolver()
export class MessageResolver {
  private message = 'Hello World';

  @Query(() => String)
  getMessage() {
    return this.message;
  }

  @Mutation(() => String)
  setMessage(@Args('newMessage') newMessage: string) {
    this.message = newMessage;
    return this.message;
  }
}
OutputSuccess
Important Notes

Resolvers should be simple and focused on handling one type of data or action.

Use @Args to get input values from GraphQL queries or mutations.

Keep your resolver methods fast and avoid heavy processing inside them.

Summary

Resolvers connect GraphQL requests to your app's data or actions.

Use @Resolver, @Query, and @Mutation decorators to define them.

Resolvers help keep your code organized and easy to understand.