GraphQl是一种新的API 的查询语言,它提供了一种更高效、强大和灵活API 查询,下面给大家讲讲在Nestjs中使用Graphql
Nestjs中使用Graphql官方文档: https://docs.nestjs.com/graphql/quick-start
$ npm i --save @nestjs/graphql graphql-tools graphql
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 }
通过命令创建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) } }
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; } }
export class Cat { id: number; name: string; age: number; }
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 {}
// 发送 query { hello } // 返回 { "data": { "hello": "hello nest.js" } }