import * as bodyParser from "body-parser"; import * as cors from 'cors'; import * as express from "express"; import { initialize } from "express-openapi"; import { assignIn } from 'lodash'; import { Logger } from 'winston'; import { EventLayer } from "../lib/communication/eventLayer"; import { getDispatcher } from "../lib/dispatcher/nopeDispatcher"; import { apiDoc } from '../specs/apiDoc'; import { getBackendAccesors } from './getBackendAccessors'; export function startBackend(options: { port?: number, basePath?: string, logger?: Logger, } = {}) { const app: express.Application = (express as any)(); // Define the Default Options const defaults = { port: 3001, basePath: '/api' } // Mix the Options. const opts = assignIn(defaults, options); app.use(bodyParser.json()); app.use(cors()); initialize({ apiDoc: apiDoc('Backend API', '1.0.0', opts.basePath), app, paths: './dist/open-api', routesGlob: '**/*.{ts,js}', routesIndexFileRegExp: /(?:index)?\.[tj]s$/, dependencies: { _dispatcher: getDispatcher('backend', new EventLayer()) }, }); app.use(((err, req, res, next) => { res.status(err.status).json(err); }) as express.ErrorRequestHandler); const server = app.listen(opts.port); const accessor = getBackendAccesors(app); if (options.logger) { options.logger.info('Server Running on http://localhost:' + opts.port.toString() + opts.basePath); options.logger.info('API Documentation available on http://localhost:' + opts.port.toString() + opts.basePath + '/api-docs'); options.logger.debug('Checkout http://localhost:3000/docs') } return { app, // Accessor for the Server accessor, // Function to extract the Definitions. definitionUri: opts.basePath + '/api-docs', // Function to Close the Server close() { server.close(); } } }