/** Backend Entrypoint This is the main entrypoint for the backend API. In here we mound the Admin, an API, ... and start the server. */ import { Admin } from "@swirl/admin"; import { API, CORSOptions } from "@swirl/api"; import * as express from "express"; import * as path from "path"; import * as bodyParser from "body-parser"; import { Server } from "http"; import { Socket } from "net"; // Setup the application export const app = express(); // Detect if there is a CORs origin to be registered let corsOptions: CORSOptions; if(process.env['CORS_ORIGIN'] != null && process.env['CORS_ORIGIN'].trim() != '') { console.log(`Enabling CORs at ${process.env['CORS_ORIGIN'].trim()}`); corsOptions = { origin: process.env['CORS_ORIGIN'].trim(), headers: ['X-Swirl-CSRF-Key'] }; } // Attach the admin let redirectUrl = '/'; if(corsOptions != null) { redirectUrl = process.env['CORS_ORIGIN'].trim(); } export const admin = new Admin({ mongoUrl: process.env['MONGO_URL'], redisUrl: process.env['REDIS_URL'], loginRedirect: redirectUrl, logoutRedirect: redirectUrl, cookieDomain: 'http://localhost:4200' }); app.use('/user', admin.router); // Attach the API export const api = new API(path.resolve(__dirname, 'api'), { cors: corsOptions }); app.use('/api', admin.inject()); app.use('/api', bodyParser.json()); app.use('/api', api.handler()); // Use index.html for everything else let appFolder = process.env['APP_FOLDER']; if(appFolder != null && appFolder.trim() != '') { app.use(express.static(appFolder)); app.use('*', (req, res) => { res.setHeader('Content-Type', 'text/html'); res.sendFile(path.resolve(appFolder, 'index.html')) }); } // Handle stop signals let server: Server; let sockets: Set = new Set(); process.on('SIGINT', () => { console.log('\nStopping...'); if(server != null) { server.close(); for(let socket of sockets) { socket.destroy(); socket.unref(); } } console.log('Finished'); }); // Start the server export let port = parseInt(process.env['HTTP_PORT'], 10); if(isNaN(port)) port = 80; server = app.listen(port, () => { console.log(`Running on port ${port}`); // Keep track of the connected sockets server.on('connection', (socket) => { if(!sockets.has(socket)) sockets.add(socket); socket.on('close', () => { sockets.delete(socket); }); }); });