Nestjs Graphql

文档
工作示例

安装依赖:

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;
}

转载于:https://www.cnblogs.com/ajanuw/p/10343127.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值