0
0
NestJSframework~30 mins

Queries and mutations in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Building Queries and Mutations in NestJS GraphQL
📖 Scenario: You are creating a simple NestJS GraphQL API for a bookstore. You want to let users get book details and add new books.
🎯 Goal: Build a NestJS GraphQL resolver with a query to get a book by its id and a mutation to add a new book with title and author.
📋 What You'll Learn
Create a Book class with id, title, and author fields
Create a query called getBook that takes an id argument and returns the matching Book
Create a mutation called addBook that takes title and author arguments and returns the new Book
Use an in-memory array to store books
💡 Why This Matters
🌍 Real World
Building APIs with NestJS and GraphQL is common for modern web apps that need flexible data fetching and updating.
💼 Career
Understanding queries and mutations in NestJS GraphQL is essential for backend developers working with GraphQL APIs.
Progress0 / 4 steps
1
Create the Book class and initial books array
Create a class called Book with id (number), title (string), and author (string) fields. Then create a variable called books as an array with one book: { id: 1, title: '1984', author: 'George Orwell' }.
NestJS
Need a hint?

Define a TypeScript class with the three fields. Then create an array with one object matching the class.

2
Add a query method to get a book by id
Add a method called getBook inside a resolver class BooksResolver. It should take an id argument of type number and return the book from books with that id. Use @Query(() => Book) decorator on the method.
NestJS
Need a hint?

Use @Resolver and @Query decorators. Use @Args to get the id argument.

3
Add a mutation method to add a new book
Inside the BooksResolver class, add a method called addBook with title and author string arguments. It should create a new Book with a unique id, add it to books, and return the new book. Use @Mutation(() => Book) decorator on the method.
NestJS
Need a hint?

Use @Mutation decorator. Create a new book object with a new id and add it to the books array.

4
Complete the resolver export and imports
Add the necessary imports from @nestjs/graphql at the top: Resolver, Query, Args, Int, and Mutation. Export the BooksResolver class so it can be used in the NestJS module.
NestJS
Need a hint?

Make sure all decorators are imported and the resolver class is exported.