UNPKG

@haku-sci/utils

Version:

utils from haku-sci. Library only

68 lines 2.95 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Microservice = void 0; const common_1 = require("@nestjs/common"); const core_1 = require("@nestjs/core"); const microservices_1 = require("@nestjs/microservices"); const net = require("net"); const utils = require("../utils"); const exceptionFilter_1 = require("./exceptionFilter"); const os = require("os"); const consul_1 = require("./consul"); const tcp_service_1 = require("../TCP/tcp.service"); class Microservice { static async bootstrapMicroservice(appModule) { this.logger = new common_1.Logger(await utils.microServiceName()); await this.setServerAddress(); if (process.env.SQL_DB && process.env.DEBUG) { const postGresService = require('./postgres.service'); postGresService.createDatabaseIfNotExists(); } const app = await this.startTCPMicroService(appModule); await tcp_service_1.TCPService.registerHakuSciMessageHandlers(app, this.logger); consul_1.Consul.registerService(this.serverAddress, this.logger); } static isPortFree(port) { return new Promise((resolve) => { const server = net.createServer(); server.once('error', (err) => { resolve(false); }); server.once('listening', () => { server.close(() => resolve(true)); }); server.listen(port, this.serverAddress.address); }); } static async setServerAddress() { this.serverAddress.address = process.env.ADDRESS || process.env.DEBUG && "127.0.0.1" || Object.values(os.networkInterfaces()) .flatMap((iface) => iface ?? []) .find((addr) => addr.family === 'IPv4' && !addr.internal) .address; if (parseInt(process.env.TCP_PORT)) this.serverAddress.port = parseInt(process.env.TCP_PORT); else while (!await this.isPortFree(this.serverAddress.port)) this.serverAddress.port++; this.logger.log("address to be listened to: " + this.serverAddress.address); this.logger.log("port to be listened to: " + this.serverAddress.port); } static async startTCPMicroService(appModule) { const app = await core_1.NestFactory.createMicroservice(appModule, { transport: microservices_1.Transport.TCP, options: { port: this.serverAddress.port, host: this.serverAddress.address, }, }); app.useGlobalFilters(new exceptionFilter_1.AllExceptionsFilter(this.logger)); await app.listen(); return app; } static get host() { return `${this.serverAddress.address}:${this.serverAddress.port}`; } } exports.Microservice = Microservice; Microservice.serverAddress = { family: 'IPv4', port: 3000, address: null }; //# sourceMappingURL=microservice.service.js.map