@nahkies/typescript-express-runtime
Version:
Runtime package for code generated by @nahkies/openapi-code-generator using the typescript-express template
80 lines • 2.71 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExpressRuntimeResponse = exports.SkipResponse = void 0;
exports.startServer = startServer;
const tslib_1 = require("tslib");
const cors_1 = tslib_1.__importDefault(require("cors"));
const express_1 = tslib_1.__importDefault(require("express"));
exports.SkipResponse = Symbol("skip response processing");
class ExpressRuntimeResponse {
status;
_body;
constructor(status) {
this.status = status;
}
body(body) {
this._body = body;
return this;
}
unpack() {
return { status: this.status, body: this._body };
}
}
exports.ExpressRuntimeResponse = ExpressRuntimeResponse;
/**
* Starts an Express 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 Express 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, notFoundHandler, errorHandler, }) {
const app = (0, express_1.default)();
if (cors !== "disabled") {
app.use((0, cors_1.default)(cors));
app.options("*route", (0, cors_1.default)(cors));
}
if (body !== "disabled") {
app.use(express_1.default.json(body?.json));
app.use(express_1.default.text(body?.text));
app.use(express_1.default.urlencoded(body?.urlencoded ?? { extended: true }));
}
if (middleware) {
for (const it of middleware) {
app.use(it);
}
}
app.use(router);
if (notFoundHandler) {
app.use(notFoundHandler);
}
if (errorHandler) {
app.use(errorHandler);
}
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
;