Skip to content

Commit

Permalink
feat(microservices) add getClientByServiceName to client grpc
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilmysliwiec committed Sep 10, 2019
1 parent d3bea8a commit 73c1cf3
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 12 deletions.
37 changes: 25 additions & 12 deletions packages/microservices/client/client-grpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ let grpcProtoLoaderPackage: any = {};

export class ClientGrpcProxy extends ClientProxy implements ClientGrpc {
protected readonly logger = new Logger(ClientProxy.name);
protected readonly clients = new Map<string, any>();
protected readonly url: string;
protected grpcClient: any;

Expand All @@ -38,6 +39,25 @@ export class ClientGrpcProxy extends ClientProxy implements ClientGrpc {
}

public getService<T extends {}>(name: string): T {
const grpcClient = this.createClientByServiceName(name);
const protoMethods = Object.keys(this.grpcClient[name].prototype);
const grpcService = {} as T;

protoMethods.forEach(m => {
const key = m[0].toLowerCase() + m.slice(1, m.length);
grpcService[key] = this.createServiceMethod(grpcClient, m);
});
return grpcService;
}

public getClientByServiceName<T = any>(name: string): T {
return this.clients.get(name) || this.createClientByServiceName(name);
}

public createClientByServiceName(name: string) {
if (!this.grpcClient[name]) {
throw new InvalidGrpcServiceException();
}
const maxSendMessageLengthKey = 'grpc.max_send_message_length';
const maxReceiveMessageLengthKey = 'grpc.max_receive_message_length';
const maxMessageLengthOptions = {
Expand All @@ -62,24 +82,17 @@ export class ClientGrpcProxy extends ClientProxy implements ClientGrpc {
...maxMessageLengthOptions,
};

if (!this.grpcClient[name]) {
throw new InvalidGrpcServiceException();
}
const credentials =
options.credentials || grpcPackage.credentials.createInsecure();
delete options.credentials;

const { credentials: originalCreds, ...clientOptions } = options;
const grpcClient = new this.grpcClient[name](
this.url,
credentials,
options,
clientOptions,
);
const protoMethods = Object.keys(this.grpcClient[name].prototype);
const grpcService = {} as T;
protoMethods.forEach(m => {
const key = m[0].toLowerCase() + m.slice(1, m.length);
grpcService[key] = this.createServiceMethod(grpcClient, m);
});
return grpcService;
this.clients.set(name, grpcClient);
return grpcClient;
}

public createServiceMethod(
Expand Down
1 change: 1 addition & 0 deletions packages/microservices/interfaces/client-grpc.interface.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export interface ClientGrpc {
getService<T extends {}>(name: string): T;
getClientByServiceName<T = any>(name: string): T;
}

0 comments on commit 73c1cf3

Please sign in to comment.