Nestjs Graphql

文档
工作示例

安装依赖:

npm i --save @nestjs/graphql apollo-server-express graphql-tools graphql

app.module.ts

import { Module } from '@nestjs/common';
// import { AppController } from './app.controller';
import { AppService } from './app.service';

import { GraphQLModule } from '@nestjs/graphql';
import { AppResolver } from './app.resolvers';

@Module({
  imports: [
    GraphQLModule.forRoot({
      typePaths: ['./**/*.graphql'],
    }),
  ],
  // controllers: [AppController],
  providers: [AppService, AppResolver],
})
export class AppModule {}

定义 typeDefs :

// app.graphql
type Query {
  hello: String
}

定义 resolvers :

// app.resolvers.ts
import { Query, Resolver } from '@nestjs/graphql';

@Resolver()
export class AppResolver {
  constructor() {}

  @Query()
  hello(): string {
    return 'hello nest.js';
  }
}

启动服务器,访问 http://localhost:5000/graphql

// 发送
query { hello }

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

猜你喜欢

转载自www.cnblogs.com/ajanuw/p/10343127.html