Files
openstapps/src/cli.ts
2021-04-27 13:02:11 +02:00

114 lines
2.9 KiB
TypeScript

/*
* Copyright (C) 2019 StApps
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {Logger} from '@openstapps/logger';
import express from 'express';
import http from 'http';
import {configureApp} from './app';
import {Elasticsearch} from './storage/elasticsearch/elasticsearch';
const app = express();
/**
* Get port from environment and store in Express.
*/
// tslint:disable-next-line: strict-boolean-expressions
const port = normalizePort(process.env.PORT || '3000');
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Define server handling for specific events
*/
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(value: string) {
const portNumber = parseInt(value, 10);
if (isNaN(portNumber)) {
// named pipe
return value;
}
if (portNumber >= 0) {
// port number
return portNumber;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
// tslint:disable-next-line: completed-docs
async function onError(error: { code: string; syscall: string; }) {
if (error.syscall !== 'listen') {
throw error;
}
const bind = typeof port === 'string'
? `Pipe ${port}`
: `Port ${port}`;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
await Logger.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
await Logger.error(`${bind} is already in use`);
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
const addr = server.address();
if (addr !== null) {
const bind = typeof addr === 'string'
? `pipe ${addr}`
: `port ${addr.port}`;
Logger.ok(`Listening on ${bind}`);
} else {
// tslint:disable-next-line: no-floating-promises
Logger.error(`Failed to start binding`);
}
}
configureApp(app, {elasticsearch: Elasticsearch})
.then(() => {
Logger.ok('Successfully configured express server');
// After app setup listen on provided port, on all network interfaces
server.listen(port);
})
.catch((err) => {
throw err;
});