feat: centralize grpc client registration
All checks were successful
Publish / Publish Job (push) Successful in 44s
All checks were successful
Publish / Publish Job (push) Successful in 44s
This commit is contained in:
36
lib/grpc/factory/grpc-client.factory.ts
Normal file
36
lib/grpc/factory/grpc-client.factory.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Injectable } from '@nestjs/common'
|
||||
import {
|
||||
ClientGrpc,
|
||||
ClientProxyFactory,
|
||||
Transport
|
||||
} from '@nestjs/microservices'
|
||||
|
||||
@Injectable()
|
||||
export class GrpcClientFactory {
|
||||
private clients = new Map<string, ClientGrpc>()
|
||||
|
||||
public createClient(options: {
|
||||
package: string
|
||||
protoPath: string
|
||||
url: string
|
||||
}) {
|
||||
return ClientProxyFactory.create({
|
||||
transport: Transport.GRPC,
|
||||
options
|
||||
}) as ClientGrpc
|
||||
}
|
||||
|
||||
public register(token: string, client: ClientGrpc) {
|
||||
this.clients.set(token, client)
|
||||
}
|
||||
|
||||
public getClient<T extends ClientGrpc = ClientGrpc>(token: string): T {
|
||||
const client = this.clients.get(token)
|
||||
|
||||
if (!client) {
|
||||
throw new Error(`gRPC client with token ${token} not found`)
|
||||
}
|
||||
|
||||
return client as T
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user