UNPKG

@nahkies/typescript-koa-runtime

Version:

Runtime package for code generated by @nahkies/openapi-code-generator using the typescript-koa template

71 lines 2.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.KoaRuntimeResponse = exports.SkipResponse = void 0; exports.startServer = startServer; const tslib_1 = require("tslib"); const cors_1 = tslib_1.__importDefault(require("@koa/cors")); const koa_1 = tslib_1.__importDefault(require("koa")); const koa_body_1 = tslib_1.__importDefault(require("koa-body")); exports.SkipResponse = Symbol("skip response processing"); class KoaRuntimeResponse { status; _body; constructor(status) { this.status = status; } body(body) { this._body = body; return this; } unpack() { return { status: this.status, body: this._body }; } } exports.KoaRuntimeResponse = KoaRuntimeResponse; /** * Starts a Koa server and listens on `port` or a randomly allocated port if none provided. * Enables CORS and body parsing by default. It's recommended to customize the CORS options * for production usage. * * If you need more control over your Koa server, you should avoid calling this function * and instead mount the router from your generated codes `createRouter` call directly * onto a server you have constructed. */ async function startServer({ middleware = [], cors = undefined, body = undefined, port = 0, router, }) { const app = new koa_1.default(); if (cors !== "disabled") { app.use((0, cors_1.default)(cors)); } if (body !== "disabled") { app.use((0, koa_body_1.default)(body)); } for (const it of middleware) { app.use(it); } app.use(router.allowedMethods()); app.use(router.routes()); return new Promise((resolve, reject) => { try { const server = app.listen(port); server.once("listening", () => { try { const address = server.address(); if (!address || typeof address !== "object") { throw new Error("failed to bind port"); } resolve({ app, server, address }); } catch (err) { reject(err); } }); server.once("error", (err) => { reject(err); }); } catch (err) { reject(err); } }); } //# sourceMappingURL=server.js.map