Introduction
Queries and mutations let you get and change data in your app. Queries fetch data, mutations update or add data.
Queries and mutations let you get and change data in your app. Queries fetch data, mutations update or add data.
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.
import { Query, Resolver } from '@nestjs/graphql'; @Resolver() export class UserResolver { @Query(() => String) hello() { return 'Hello World'; } }
import { Mutation, Resolver, Args } from '@nestjs/graphql'; @Resolver() export class UserResolver { @Mutation(() => Boolean) updateName(@Args('name') name: string) { // pretend to update name return true; } }
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.
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}`; } }
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.
Queries fetch data without changing it.
Mutations change data and can return results.
Use decorators @Query and @Mutation in NestJS GraphQL resolvers.
createUser in a NestJS GraphQL resolver?getUser query is called?@Query(() => String)
getUser() {
return 'Alice';
}@Mutation(() => Boolean)
async updateUser() {
this.userService.update();
return true;
}Pass the test and this pattern moves unknown