Nestjs Graphql

GraphQl是一种新的API 的查询语言,它提供了一种更高效、强大和灵活API 查询,下面给大家讲讲在Nestjs中使用Graphql

Nestjs中使用Graphql官方文档: https://docs.nestjs.com/graphql/quick-start

1、Nestjs中安装操作Graphql的模块

 $ npm i --save @nestjs/graphql graphql-tools graphql
        

2、定义操作数据库的Schema

src目录下面新建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
}
 

3、定义 resolvers 操作数据库的方法

通过命令创建resolvers

nest g resolver app
        
这样会在src目录下面生成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)
  }
}
        

4、定义 服务 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;
  }
}
        

5、定义接口 graphql.schema.ts (非必须)


export class Cat {
  id: number;
  name: string;
  age: number;
}
        

6、配置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'],   //加载目录下面所有以graphql结尾的schema文件,当做固定写法
    }), 
  ],
  providers: [AppService, AppResolver],
})
export class AppModule {}
        

7、操作graphql数据库

// 发送
query { hello }

// 返回
{
  "data": {
    "hello": "hello nest.js"
  }
}