52 lines
1.3 KiB
TypeScript
52 lines
1.3 KiB
TypeScript
|
import { apiDoc } from '../specs/apiDoc';
|
||
|
import * as express from "express";
|
||
|
import * as bodyParser from "body-parser";
|
||
|
import { initialize } from "express-openapi";
|
||
|
import { getBackendAccesors } from './getBackendAccessors';
|
||
|
import { assignIn } from 'lodash';
|
||
|
|
||
|
export function startBackend(options: {
|
||
|
port?: number,
|
||
|
basePath?: string,
|
||
|
}= {}) {
|
||
|
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());
|
||
|
|
||
|
initialize({
|
||
|
apiDoc: apiDoc('Test API', '0.0.1', opts.basePath),
|
||
|
app,
|
||
|
paths: './dist/api',
|
||
|
routesGlob: '**/*.{ts,js}',
|
||
|
routesIndexFileRegExp: /(?:index)?\.[tj]s$/
|
||
|
});
|
||
|
|
||
|
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);
|
||
|
|
||
|
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();
|
||
|
}
|
||
|
}
|
||
|
}
|