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.
Code-first approach in 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.
import { ObjectType, Field } from '@nestjs/graphql'; @ObjectType() export class User { @Field() username: string; @Field() email: string; }
import { ObjectType, Field, Int } from '@nestjs/graphql'; @ObjectType() export class Post { @Field(type => Int) id: number; @Field() title: string; @Field({ nullable: true }) content?: string; }
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.
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; } }
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.
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.