安装依赖:
npm i --save @nestjs/graphql apollo-server-express graphql-tools graphql
app.module.ts
import { Module } from '@nestjs/common';
import { AppService } from './app.service';
import { GraphQLModule } from '@nestjs/graphql';
import { AppResolver } from './app.resolvers';
@Module({
imports: [
GraphQLModule.forRoot({
typePaths: ['./**/*.graphql'],
}),
],
providers: [AppService, AppResolver],
})
export class AppModule {}
定义 typeDefs :
// app.graphql
type Query {
hello: String
findCat(id: ID): Cat
cats: [Cat]
}
type Cat {
id: Int
name: String
age: Int
}
type Mutation {
addCat(cat: InputCat): Cat
}
input InputCat {
name: String
age: Int
}
定义 resolvers :
// app.resolvers.ts
import { ParseIntPipe } from '@nestjs/common';
import { Query, Resolver, Args, Mutation } from '@nestjs/graphql';
import { AppService } from './app.service';
@Resolver()
export class AppResolver {
constructor(private readonly appService: AppService) {}
// query { hello }
@Query()
hello(): string {
return this.appService.hello();
}
// query { findCat(id: 1) { name age } }
// 网络传输过来的id会是字符串类型,而不是number
@Query('findCat')
findOneCat(@Args('id', ParseIntPipe) id: number) {
return this.appService.findCat(id);
}
// query { cats { id name age } }
@Query()
cats() {
return this.appService.findAll();
}
// mutation { addCat(cat: {name: "ajanuw", age: 12}) { id name age } }
@Mutation()
addCat(@Args('cat') args) {
console.log(args);
return this.appService.addCat(args)
}
}
启动服务器,访问 http://localhost:5000/graphql
// 发送
query { hello }
// 返回
{
"data": {
"hello": "hello nest.js"
}
}
app.service.ts
import { Injectable } from '@nestjs/common';
import { Cat } from './graphql.schema';
@Injectable()
export class AppService {
private readonly cats: Cat[] = [
{ id: 1, name: 'a', age: 1 },
{ id: 2, name: 'b', age: 2 },
];
hello(): string {
return 'Hello World!';
}
findCat(id: number): Cat {
return this.cats.find(c => c.id === id);
}
findAll(): Cat[] {
return this.cats;
}
addCat(cat: Cat): Cat {
const newCat = { id: this.cats.length + 1, ...cat };
console.log(newCat);
this.cats.push(newCat);
return newCat;
}
}
graphql.schema.ts
export class Cat {
id: number;
name: string;
age: number;
}