Code-first Resolvers

Setup

Example

npm i @nestjs/graphql @nestjs/apollo @apollo/server graphql

Example output

added 46 packages in 7s
// app.module.ts
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { GraphQLModule } from '@nestjs/graphql';
import { join } from 'node:path';

@Module({
  imports: [
    GraphQLModule.forRoot<ApolloDriverConfig>({
      driver: ApolloDriver,
      autoSchemaFile: join(process.cwd(), 'src/schema.gql'),   // code-first: schema generated from classes
      sortSchema: true,
    }),
  ],
})
export class AppModule {}

Types and a Resolver

src/products/models/product.model.ts and src/products/products.resolver.ts

import { Args, Field, Float, ID, InputType, Int, Mutation, ObjectType, Parent, Query, ResolveField, Resolver } from '@nestjs/graphql';
import { IsPositive, Length } from 'class-validator';

@ObjectType()
export class CategoryModel {
  @Field(() => ID) id: number;
  @Field() name: string;
}

@ObjectType()
export class ProductModel {
  @Field(() => ID) id: number;
  @Field() name: string;
  @Field(() => Float) price: number;
  @Field(() => Int) stock: number;
  @Field(() => CategoryModel) category: CategoryModel;
  categoryId: number;                                   // not exposed
}

@InputType()
export class CreateProductInput {
  @Field() @Length(3, 120) name: string;
  @Field(() => Float) @IsPositive() price: number;
  @Field(() => Int) categoryId: number;
}

@Resolver(() => ProductModel)
export class ProductsResolver {
  constructor(private readonly products: ProductsService, private readonly categories: CategoriesService) {}

  @Query(() => [ProductModel])
  products(@Args('category', { nullable: true }) category?: string) {
    return this.products.findAll(category);
  }

  @Query(() => ProductModel, { nullable: true })
  product(@Args('id', { type: () => Int }) id: number) {
    return this.products.findOne(id);
  }

  @Mutation(() => ProductModel)
  createProduct(@Args('input') input: CreateProductInput) {
    return this.products.create(input);
  }

  @ResolveField(() => CategoryModel)
  category(@Parent() product: ProductModel) {
    return this.categories.findById(product.categoryId);
  }
}

Example

curl -s http://localhost:3000/graphql -H "Content-Type: application/json" \
  -d '{"query":"{ products(category: \"audio\") { id name price category { name } } }"}'

Example output

{"data":{"products":[{"id":"7","name":"boAt Airdopes 141","price":1299,"category":{"name":"Audio"}},{"id":"12","name":"OnePlus Nord Buds 2","price":2299,"category":{"name":"Audio"}}]}}