0
0
NestJSframework~30 mins

Object types and input types in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
NestJS Object Types and Input Types
📖 Scenario: You are building a simple NestJS API to manage a list of books in a library. Each book has a title and an author.We will create object types to represent the book data and input types to handle new book creation requests.
🎯 Goal: Create a NestJS GraphQL object type for Book and an input type for CreateBookInput. Then use these types in a resolver to add new books.
📋 What You'll Learn
Create a GraphQL object type called Book with fields title and author of type string.
Create a GraphQL input type called CreateBookInput with fields title and author of type string.
Create a resolver method called addBook that takes CreateBookInput as an argument and returns a Book.
Use decorators @ObjectType(), @Field(), and @InputType() correctly.
💡 Why This Matters
🌍 Real World
APIs often need to define clear data structures for input and output. NestJS GraphQL uses object types and input types to do this cleanly.
💼 Career
Understanding how to create and use object and input types in NestJS GraphQL is essential for backend developers working with modern APIs.
Progress0 / 4 steps
1
Create the Book object type
Create a class called Book decorated with @ObjectType(). Add two string fields: title and author, each decorated with @Field().
NestJS
Need a hint?

Use @ObjectType() above the class and @Field() above each property.

2
Create the CreateBookInput input type
Create a class called CreateBookInput decorated with @InputType(). Add two string fields: title and author, each decorated with @Field().
NestJS
Need a hint?

Use @InputType() above the class and @Field() above each property.

3
Create the addBook resolver method
In a resolver class called BooksResolver, create a method called addBook decorated with @Mutation(() => Book). It should take one argument called createBookInput of type CreateBookInput decorated with @Args('createBookInput'). The method should return a new Book object with the same title and author as createBookInput.
NestJS
Need a hint?

Use @Mutation(() => Book) above the method and @Args('createBookInput') for the argument.

4
Export the resolver and complete setup
Export the BooksResolver class and ensure all imports are correct. This completes the setup for object types and input types in NestJS GraphQL.
NestJS
Need a hint?

Use export { BooksResolver }; at the end of the file.