import bodyParser from 'body-parser' ; import crypto from 'crypto' ; import express from 'express' ; import session from 'express-session' ; import helmet from 'helmet' ; import http from 'http' ; import morgan from 'morgan' ; import favicon from 'serve-favicon' ; import { LogInstance } from 'log/loginstance' ; import { MorganToWinstonStream } from 'log/morgan2winston' ; import { PagesController } from 'controller/pages' ; import { ActionsController } from 'controller/actions' ; import { MapImageList } from 'maps' ; import { ROBOTS_TXT_CONTENT } from 'config/robots' ; const sessionSettings = { secret : crypto . randomBytes ( 32 ) . toString ( 'hex' ) , name : 'cso2-web-session' , cookie : { maxAge : 1000 * 60 * 30 , sameSite : true } , resave : false , saveUninitialized : false } ; /**
 * the service's entrypoint
 */ export class ServiceInstance { public app : express . Express ; private server : http . Server ; constructor ( ) { this . app = express ( ) ; this . applyConfigs ( ) ; this . setupRoutes ( ) ; this . app . set ( 'port' , process . env . WEBSITE_PORT ) ; } /**
     * start the service
     */ public async listen ( ) { await MapImageList . build ( ) ; LogInstance . info ( `Found ${ MapImageList . getNumOfFiles ( ) } map images` ) ; this . server = this . app . listen ( this . app . get ( 'port' ) ) ; LogInstance . info ( 'Started web page service' ) ; LogInstance . info ( `Listening at ${ this . app . get ( 'port' ) as number }` ) ; } /**
     * stop the service instance
     */ public stop ( ) { this . server . close ( ) ; } /**
     * apply configurations to the service
     */ private applyConfigs ( ) { let morganLogFormat = '' ; if ( this . isDevEnv ( ) ) { morganLogFormat = 'dev' ; sessionSettings . cookie . secure = false ; } else { morganLogFormat = 'common' ; } this . app . use ( morgan ( morganLogFormat , { stream : new MorganToWinstonStream ( ) } ) ) ; this . app . use ( bodyParser . json ( ) ) ; this . app . use ( bodyParser . urlencoded ( { extended : true } ) ) ; this . app . use ( helmet ( { frameguard : false } ) ) ; this . app . use ( session ( sessionSettings ) ) ; this . app . set ( 'views' , 'src/views' ) ; this . app . set ( 'view engine' , 'pug' ) ; this . app . use ( '/static' , express . static ( 'public' , { } ) ) ; this . setupRobots ( ) ; this . app . use ( favicon ( 'public/favicon.ico' ) ) ; } /**
     * setup the service's API routes
     */ private setupRoutes ( ) { PagesController . setup ( this . app ) ; ActionsController . setup ( this . app ) ; } private setupRobots ( ) { this . app . get ( '/robots.txt' , ( req , res ) => { res . type ( 'text/plain' ) ; res . send ( ROBOTS_TXT_CONTENT ) ; res . end ( ) ; } ) ; } returns private isDevEnv ( ) { return process . env . NODE_ENV === 'development' ; } }