'use strict'; /** * ExpressJS Controller */ require('dotenv').config(); const express = require('express'); const cors = require('cors'); const compression = require('compression'); const morgan = require('morgan'); const helmet = require('helmet'); const bodyParser = require('body-parser'); const fileUpload = require('express-fileupload'); /// Import Applications to serve const AppsController = require('../../Controller'); const middlewares = require('./middlewares'); const UNINIT = 0; const INIT = 1; const ONLINE = 2; const OFFLINE = 3; class ExpressJSServices { constructor(){ this.SystemServiceState = UNINIT; this.serverPort = process.env.SERVER_PORT || 3000; this.app = express(); } async setup(){ const app = this.app; await AppsController.setup(); app.use( middlewares.Auth ); app.use( fileUpload({ limits: { fileSize: 4 * 1024 * 1024 }, abortOnLimit: true, limitHandler: (req,res,next) => { req.limitSize = true; }, }) ); app.use((req, res, next) => { if (req.limitSize) { res.status(413).send({message:"File size limit has been reached",status:"PAYLOAD_TOO_LARGE"}); }else{ next() } }); app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' })); app.use(bodyParser.json({ limit: '50mb' })); app.use(morgan('dev')); app.use(helmet({ crossOriginResourcePolicy: false })); app.use(compression()); app.use(cors({ origin: '*', methods: [ 'GET', 'POST', 'PATCH', 'PUT', 'DELETE' ], allowedHeaders: ['Content-Type', 'Authorization'] })); this.SystemServiceState = UNINIT; } async init(){ const app = this.app; await AppsController.init(); app.use( middlewares.errorJSON ); app.use( AppsController.app_controller() ); app.use( middlewares.error404 ); this.SystemServiceState = INIT; } async connect(){ const app = this.app; const serverPort = this.serverPort; await AppsController.connect(); const server = app.listen( serverPort , function(err){ if( !err ){ console.log('API listen on port', serverPort ); }else{ console.log( err ); } }); this.server = server; this.SystemServiceState = ONLINE; } async disconnect(){ await AppsController.disconnect(); this.server.close(); this.SystemServiceState = OFFLINE; } async deinit(){ await AppsController.deinit(); this.SystemServiceState = UNINIT; } async getState(){ switch( this.SystemServiceState ){ case UNINIT: return "UNINIT"; case INIT: return "INIT"; case ONLINE: return "ONLINE"; case OFFLINE: return "OFFLINE"; default: return "UNINIT"; } } } module.exports = new ExpressJSServices();