NestJS integrated graphql grpc distributed practice

Keywords: node.js npm


In order to learn the knowledge of nestjs graphql grpc microservice, the specific syntax of grpc and graphql is analyzed in detail

1 create project

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

2 add graphql

Create graphql-config.service.ts file for graphql configuration and filter writing logic

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

  createGqlOptions(): GqlModuleOptions {
    return {
      typePaths: [join(process.cwd(), "./graphqls/*.graphql")],  //  Configured graphql file address
      installSubscriptionHandlers: true,
      definitions: {
        path: join(process.cwd(), "src/graphql.schema.ts"),  // Resolved file address
        outputAs: "class"
      },
      context: async ({ req }) => { // Filter
        let user = Jwt.verifyToken(req.headers.authorization);
        // Business logic
        return { user };
      }
    };
  }
}

Add to app.module.ts

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

Create file xxx.resolvers.ts

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

3 add grpc
First, create a subproject xxx

Sub item
Create the grpc.options.ts file for init connection configuration

export const grpcClientOptions: ClientOptions = {
  transport: Transport.GRPC,
  options: {
    url: "localhost:50051",  // Service address
    package: "xxx",
    protoPath: join(__dirname, './xxx.proto'),
  },
};

Create the interface, notice that the initial here is automatically capitalized

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

Import in main.ts

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

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

Other microservices or apigateway calls create a

 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;
}

Posted by Bac on Sun, 01 Dec 2019 05:51:29 -0800