3

图片描述

前言:

为了学习nestjs graphql grpc 微服务方面的知识,具体grpc和graphql的语法再之后在做详细分析

1 创建项目

npm i -g @nestjs/cli
nest new project-name

2 添加graphql

创建graphql-config.service.ts文件,用于graphql的配置及编写过滤器的逻辑

@Injectable()
export class GraphQLConfigService implements GqlOptionsFactory {
  constructor() {}

  createGqlOptions(): GqlModuleOptions {
    return {
      typePaths: [join(process.cwd(), "./graphqls/*.graphql")],  //  配置的graphql文件地址
      installSubscriptionHandlers: true,
      definitions: {
        path: join(process.cwd(), "src/graphql.schema.ts"),  // 解析之后的文件地址
        outputAs: "class"
      },
      context: async ({ req }) => { // 过滤器
        let user = Jwt.verifyToken(req.headers.authorization);
        // 业务逻辑
        return { user };
      }
    };
  }
}

添加进app.module.ts里

@Module({
  imports: [
    GraphQLModule.forRootAsync({
      imports: [ApplicationModule],
      useClass: GraphQLConfigService
    }),
  ],
})
export class ApplicationModule {}

创建文件xxx.resolvers.ts

  @Query('getUser')
  async getUser() {
    return {};
  }

3 添加grpc

首先,创建一个子项目xxx

子项目
创建grpc.options.ts文件,用于init连接的配置

export const grpcClientOptions: ClientOptions = {
  transport: Transport.GRPC,
  options: {
    url: “localhost:50051”,  // 服务地址
    package: “xxx”,
    protoPath: join(__dirname, './xxx.proto'),
  },
};

创建接口, 注意这里的首字母会被自动装为大写

  @GrpcMethod("UserService")
  async addUser(data: User): Promise<any> {
    return data
  }

在main.ts引入

import { grpcClientOptions } from './grpc.options';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.connectMicroservice(grpcClientOptions);
  await app.startAllMicroservicesAsync();
}
bootstrap();

其他微服务或是apigateway调用是创建一个

 const grpcClientOptions: ClientOptions = {
  transport: Transport.GRPC,
  options: {
    url: grpcServe.user.url,
    package: grpcServe.user.package,
    protoPath: join(__dirname, '../../common/proto/user.proto'),
  },
};

@Injectable()
export class ClentServe {
  constructor() {}
  @Client(grpcClientOptions) public readonly client: ClientGrpc;
}

demo地址


fuqihan
1.1k 声望9 粉丝

江湖走马,风也好,雨也罢