NestJS 集成graphql grpc 分布式实践
前言: 为了学习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; }
相关推荐
sichenglain 2020-10-27
zhyue 2020-09-28
0linker 2020-09-01
sichenglain 2020-05-19
FZEROF 2020-04-26
zehuawong 2020-04-07
zehuawong 2020-02-11
acloudhuang 2020-01-18
IT新技术 2020-01-07
wikowin 2019-12-15
FZEROF 2019-12-09
sichenglain 2019-11-21
chzh0 2019-11-19
FZEROF 2019-11-19
月光恋九霄 2019-11-18
zehuawong 2019-11-08
HelloWood 2018-09-08
zehuawong 2018-09-08
0linker 2019-10-31