0
0
NestJSframework~5 mins

Code-first approach in NestJS

Choose your learning style9 modes available
Introduction

The code-first approach lets you create your GraphQL API by writing code first. This means you define your data and logic in code, and the GraphQL schema is generated automatically.

When you want to build a GraphQL API quickly without writing schema files manually.
When you prefer to keep your API definitions close to your business logic code.
When you want automatic type safety and validation from your code classes.
When you want to use decorators to describe your GraphQL types and fields.
When you want to avoid syncing separate schema files with your code.
Syntax
NestJS
import { ObjectType, Field, Int } from '@nestjs/graphql';

@ObjectType()
export class Sample {
  @Field(type => Int)
  id: number;

  @Field()
  name: string;
}

@ObjectType marks a class as a GraphQL type.

@Field marks class properties as GraphQL fields and can specify their types.

Examples
This defines a simple User type with two string fields.
NestJS
import { ObjectType, Field } from '@nestjs/graphql';

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

  @Field()
  email: string;
}
This defines a Post type with an integer id, a title, and an optional content field.
NestJS
import { ObjectType, Field, Int } from '@nestjs/graphql';

@ObjectType()
export class Post {
  @Field(type => Int)
  id: number;

  @Field()
  title: string;

  @Field({ nullable: true })
  content?: string;
}
Sample Program

This example shows a Book type and a resolver that returns a list of books. The GraphQL schema is generated from the Book class and the resolver methods.

NestJS
import { Resolver, Query } from '@nestjs/graphql';
import { ObjectType, Field, Int } from '@nestjs/graphql';

@ObjectType()
class Book {
  @Field(type => Int)
  id: number;

  @Field()
  title: string;

  @Field()
  author: string;
}

@Resolver(of => Book)
export class BookResolver {
  private books: Book[] = [
    { id: 1, title: '1984', author: 'George Orwell' },
    { id: 2, title: 'The Hobbit', author: 'J.R.R. Tolkien' },
  ];

  @Query(returns => [Book])
  books() {
    return this.books;
  }
}
OutputSuccess
Important Notes

Use decorators like @ObjectType and @Field to define your GraphQL types in code.

The code-first approach automatically creates the schema, so you don't write .graphql files.

This approach keeps your API definitions and business logic together, making maintenance easier.

Summary

The code-first approach means writing your GraphQL types and resolvers in code first.

Decorators mark classes and fields to generate the GraphQL schema automatically.

This method is great for quick development and keeping code organized.