0
0
NestJSframework~5 mins

Queries and mutations in NestJS

Choose your learning style9 modes available
Introduction

Queries and mutations let you get and change data in your app. Queries fetch data, mutations update or add data.

When you want to get a list of users from a database.
When you need to add a new product to your store.
When you want to update a user's profile information.
When you want to delete an item from a list.
When you want to fetch details about a single record.
Syntax
NestJS
import { Query, Mutation, Resolver } from '@nestjs/graphql';

@Resolver()
export class SampleResolver {
  @Query(() => ReturnType)
  getData() {
    // return data
  }

  @Mutation(() => ReturnType)
  changeData(input: InputType) {
    // update or add data
  }
}

@Query defines a method to fetch data.

@Mutation defines a method to change data.

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

@Resolver()
export class UserResolver {
  @Query(() => String)
  hello() {
    return 'Hello World';
  }
}
This mutation updates a name and returns true if successful.
NestJS
import { Mutation, Resolver, Args } from '@nestjs/graphql';

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

This resolver has a query to get all todo tasks as strings. It also has a mutation to add a new todo task and returns a confirmation message.

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

@Resolver()
export class TodoResolver {
  private todos = [{ id: 1, task: 'Learn NestJS' }];

  @Query(() => [String])
  getTodos() {
    return this.todos.map(todo => todo.task);
  }

  @Mutation(() => String)
  addTodo(@Args('task') task: string) {
    const newTodo = { id: this.todos.length + 1, task };
    this.todos.push(newTodo);
    return `Added: ${task}`;
  }
}
OutputSuccess
Important Notes

Queries should not change data, only return it.

Mutations can change data and usually return the changed data or a status.

Use @Args to get input values for mutations.

Summary

Queries fetch data without changing it.

Mutations change data and can return results.

Use decorators @Query and @Mutation in NestJS GraphQL resolvers.