adonis-grpc-consumer
Version:
Adonis gRPC client provider for easily communicate with gRPC services
100 lines (99 loc) • 3.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.GrpcConsumer = void 0;
const grpc_js_1 = require("@grpc/grpc-js");
const proto_loader_1 = require("@grpc/proto-loader");
class GrpcConsumer {
constructor(config) {
this.clients = [];
this.config = config;
/**
* For each configured client, let's create a gRPC client.
*/
this.config.clients.forEach((client) => {
if (config.verbose) {
console.log(`[GRPC] Creating gRPC client: ${client.name}`);
}
this.createGrpcClient(client);
});
}
async createGrpcClient(config) {
const { url, protoPath } = config.options;
/**
* We load the proto file and create the package definition
*/
const packageDefinition = await (0, proto_loader_1.load)(protoPath, config.options.packageDefinitionOptions);
const proto = (0, grpc_js_1.loadPackageDefinition)(packageDefinition);
const client = this.createClient(proto, config.options.package, config.options.serviceName, url, grpc_js_1.credentials.createInsecure());
if (this.config.verbose) {
console.log(`[GRPC] Trying to connect to gRPC server ${config.name} at ${url}...`);
}
/**
* We now try to connect to the gRPC server with a deadline.
*/
const deadline = new Date();
deadline.setSeconds(deadline.getSeconds() + 5);
client.waitForReady(deadline, (error) => {
if (error) {
console.log(`[GRPC] Client ${config.name} connect error: ${error.message}`);
return;
}
if (this.config.verbose) {
console.log(`[GRPC] Client ${config.name} connected !`);
}
this.clients.push({ client, config });
});
}
/**
* Split the package name into an array if it's a nested package.
*/
getPackageName(packageName) {
if (packageName.split('.').length > 1) {
return packageName.split('.');
}
else {
return packageName;
}
}
/**
* Returns the services from the given package. Handle nested package
*/
getServices(proto, packageName) {
if (packageName.length === 1) {
return proto[packageName[0]];
}
else {
return this.getServices(proto[packageName[0]], packageName.slice(1));
}
}
/**
* Creates a gRPC client.
*/
createClient(proto, packageName, serviceName, url, channelCredentials) {
const name = this.getPackageName(packageName);
const services = this.getServices(proto, name);
return new services[serviceName](url, channelCredentials);
}
/**
* Returns the gRPC client for the given name with good typings.
*/
getClient(name) {
const foundClient = this.clients.find((client) => client.config.name === name);
if (!foundClient)
return;
return foundClient.client;
}
/**
* Closes all the gRPC clients.
*/
async closeAll() {
const promises = this.clients.map((client) => {
if (this.config.verbose) {
console.log(`[GRPC] Closing gRPC client: ${client.config.name}`);
}
return client.client.close();
});
await Promise.allSettled(promises);
}
}
exports.GrpcConsumer = GrpcConsumer;