0.0.4 • Published 4 years ago

@solaria-labs/nestjs-grpc-service-factory v0.0.4

Weekly downloads
-
License
MIT
Repository
github
Last release
4 years ago

nestjs-grpc-service-factory

This project contains a utility to simplify working with the NestJS gRPC client.

Installation

$ npm install @solarialabs/nestjs-grpc-service-factory

Overview

NestJS gRPC clients are instantiated based on a remote service's gRPC package, leaving it up to the user to fetch the particular service that they are interested in in a separate step once the client has finished initializing. Take the example given by the NestJS gRPC documentation:

@Injectable()
export class AppService implements OnModuleInit {
  private heroesService: HeroesService;

  constructor(@Inject('HERO_PACKAGE') private client: ClientGrpc) {}

  onModuleInit() {
    this.heroesService = this.client.getService<HeroesService>('HeroesService');
  }

  getHero(): Observable<string> {
    return this.heroesService.findOne({ id: 1 });
  }
}

This first creates a client which can connect to the overall remote service, then in the onModuleInit method pulls out the particular gRPC service that we'll be calling. While this is convenient for pulling multiple services from a single gRPC client, it is often the case that a service will only expose a single gRPC service and so this is unecessarily verbose. That's where the GrpcServiceFactory comes in; it can be used to both create the client and retrieve a service in one step.

// server.module.ts
@Module({
  imports: [GrpcServiceFactory.create<GrpcServiceInterface>('GrpcService', grpcClientOptions)]
})
export class ServerModule {}

// server.service.ts
@Injectable()
export class ProductsService {
  constructor(
    @Inject('GrpcService') private readonly grpcService: GrpcServiceInterface
  ) {}
}