Object types and input types help define the shape of data in NestJS GraphQL. They make sure data sent and received is clear and correct.
Object types and input types in NestJS
import { ObjectType, Field, InputType } from '@nestjs/graphql'; @ObjectType() export class ExampleObject { @Field() propertyName: string; } @InputType() export class ExampleInput { @Field() inputProperty: string; }
@ObjectType() marks a class as a GraphQL object type for outputs.
@InputType() marks a class as a GraphQL input type for inputs.
import { ObjectType, Field } from '@nestjs/graphql'; @ObjectType() export class User { @Field() id: string; @Field() name: string; }
import { InputType, Field } from '@nestjs/graphql'; @InputType() export class CreateUserInput { @Field() name: string; @Field() email: string; }
This example shows a simple NestJS GraphQL resolver with an object type Book and an input type CreateBookInput. You can query all books or add a new book using the input type.
import { Resolver, Query, Mutation, Args } from '@nestjs/graphql'; import { ObjectType, Field, InputType } from '@nestjs/graphql'; @ObjectType() class Book { @Field() title: string; @Field() author: string; } @InputType() class CreateBookInput { @Field() title: string; @Field() author: string; } @Resolver() export class BookResolver { private books: Book[] = []; @Query(() => [Book]) getBooks(): Book[] { return this.books; } @Mutation(() => Book) addBook(@Args('input') input: CreateBookInput): Book { const newBook = new Book(); newBook.title = input.title; newBook.author = input.author; this.books.push(newBook); return newBook; } }
Always decorate each property with @Field() to expose it in GraphQL schema.
Input types are used for data coming into the server, object types for data going out.
You can reuse object types as input types if needed, but separate classes keep things clear.
Object types define the shape of data returned by GraphQL queries and mutations.
Input types define the shape of data clients send to the server.
Use decorators @ObjectType() and @InputType() to create these types in NestJS.