@restorecommerce/chassis-srv
Version:
Restore Commerce microservice chassis
74 lines • 2.25 kB
JavaScript
import { isNullish } from 'remeda';
import { createServer } from 'nice-grpc';
import { loggingMiddleware, metaMiddleware, tracingMiddleware } from './middlewares.js';
/**
* Name of the transport
*/
export const NAME = 'grpc';
/**
* Server transport provider.
* @class
*/
export class Server {
config;
logger;
server;
name;
isBound;
/**
* Server is a gRPC transport provider for serving.
*
* @param {Object} config Configuration object.
* Requires properties: addr
* Optional properties: credentials.ssl.certs
* @param {Logger} logger Logger.
*/
constructor(config, logger) {
if (isNullish(logger)) {
throw new Error('gRPC server transport provider requires a logger');
}
if (!('addr' in config)) {
throw new Error('server is missing addr config field');
}
this.config = config;
this.logger = logger;
this.server = createServer(config?.channelOptions)
.use(tracingMiddleware)
.use(metaMiddleware)
.use(loggingMiddleware(this.logger));
this.name = NAME;
}
/**
* bind maps the service to gRPC methods and binds the address.
*
* @param {BindConfig} config Service bind config.
*/
bind(config) {
this.server.add(config.service, config.implementation);
}
/**
* start launches the gRPC server and provides the service endpoints.
*/
async start() {
if (!this.isBound) {
// TODO Re-enable
// if (_.has(this.config, 'credentials.ssl')) {
// credentials = grpc.credentials.createSsl(
// this.config.credentials.ssl.certs);
// }
await this.server.listen(this.config.addr).catch(err => {
this.logger.error('Error starting server', { message: err.message, code: err.code, stack: err.stack });
throw err;
});
this.isBound = true;
}
}
/**
* end stops the gRPC server and no longer provides the service endpoints.
*/
async end() {
this.server.forceShutdown();
}
}
export { Server as grpcServer };
//# sourceMappingURL=index.js.map