0
0
NestJSframework~5 mins

Object types and input types in NestJS

Choose your learning style9 modes available
Introduction

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.

When creating GraphQL queries that return data objects.
When defining the structure of data clients can send to the server.
When you want to validate and type-check data in GraphQL resolvers.
When building APIs that need clear input and output data formats.
Syntax
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.

Examples
This defines a User object type with id and name fields for GraphQL responses.
NestJS
import { ObjectType, Field } from '@nestjs/graphql';

@ObjectType()
export class User {
  @Field()
  id: string;

  @Field()
  name: string;
}
This defines an input type for creating a user, specifying the data clients must send.
NestJS
import { InputType, Field } from '@nestjs/graphql';

@InputType()
export class CreateUserInput {
  @Field()
  name: string;

  @Field()
  email: string;
}
Sample Program

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.

NestJS
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;
  }
}
OutputSuccess
Important Notes

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.

Summary

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.