-
Notifications
You must be signed in to change notification settings - Fork 41
/
index.ts
52 lines (46 loc) · 1.64 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import * as grpc from 'grpc';
import {
addServerBuildMethods,
ClientFactoryConstructor,
createService,
createServiceClient,
DynamicMethods,
GenericServerBuilder,
getServiceNames,
grpcLoad,
GrpcService,
lookupPackage,
} from './utils';
export { ClientFactoryConstructor, GenericServerBuilder } from './utils';
export function serverBuilder<T>(
protoPath: string,
packageName: string,
server = new grpc.Server(),
): T & GenericServerBuilder<T> {
const adders: DynamicMethods = {};
const pkg = lookupPackage(grpcLoad(protoPath), packageName);
for (const name of getServiceNames(pkg)) {
adders[`add${name}`] = function(rxImpl: DynamicMethods) {
const serviceData = (pkg[name] as any) as GrpcService<any>;
server.addService(serviceData.service, createService(serviceData, rxImpl));
return this;
};
}
return addServerBuildMethods(adders, server) as any;
}
export function clientFactory<T>(protoPath: string, packageName: string) {
class Constructor {
readonly __args: [string, grpc.ChannelCredentials, any | undefined];
constructor(address: string, credentials?: grpc.ChannelCredentials, options: any = undefined) {
this.__args = [address, credentials || grpc.credentials.createInsecure(), options];
}
}
const prototype: DynamicMethods = Constructor.prototype;
const pkg = lookupPackage(grpcLoad(protoPath), packageName);
for (const name of getServiceNames(pkg)) {
prototype[`get${name}`] = function(this: Constructor) {
return createServiceClient((pkg[name] as any) as GrpcService<any>, this.__args);
};
}
return (Constructor as any) as ClientFactoryConstructor<T>;
}