UNPKG

@dooboostore/simple-boot-http-server

Version:
309 lines (308 loc) 16.5 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var SimpleBootHttpServer_exports = {}; __export(SimpleBootHttpServer_exports, { SimpleBootHttpServer: () => SimpleBootHttpServer }); module.exports = __toCommonJS(SimpleBootHttpServer_exports); var import_SimpleApplication = require("@dooboostore/simple-boot/SimpleApplication"); var import_HttpServerOption = require("./option/HttpServerOption"); var import_http = require("http"); var import_https = require("https"); var import_RequestResponse = require("./models/RequestResponse"); var import_MethodMapping = require("./decorators/MethodMapping"); var import_HttpStatus = require("./codes/HttpStatus"); var import_HttpHeaders = require("./codes/HttpHeaders"); var import_Mimes = require("./codes/Mimes"); var import_ExceptionDecorator = require("@dooboostore/simple-boot/decorators/exception/ExceptionDecorator"); var import_Inject = require("@dooboostore/simple-boot/decorators/inject/Inject"); var import_ReflectUtils = require("@dooboostore/core/reflect/ReflectUtils"); var import_ReqFormUrlBody = require("./models/datas/body/ReqFormUrlBody"); var import_ReqJsonBody = require("./models/datas/body/ReqJsonBody"); var import_ReqHeader = require("./models/datas/ReqHeader"); var import_RouterModule = require("@dooboostore/simple-boot/route/RouterModule"); var import_ReqMultipartFormBody = require("./models/datas/body/ReqMultipartFormBody"); var import_Validation = require("@dooboostore/simple-boot/decorators/validate/Validation"); var import_ValidException = require("@dooboostore/simple-boot/errors/ValidException"); var import_HttpError = require("./errors/HttpError"); var import_Router = require("@dooboostore/simple-boot/decorators/route/Router"); var import_url = require("url"); var import_HttpMethod = require("./codes/HttpMethod"); var import_SessionManager = require("./session/SessionManager"); var import_InjectSituationType = require("./inject/InjectSituationType"); class SimpleBootHttpServer extends import_SimpleApplication.SimpleApplication { constructor(option = new import_HttpServerOption.HttpServerOption()) { super(option); this.option = option; this.sessionManager = new import_SessionManager.SessionManager(this.option); } run(otherInstanceSim) { super.run(otherInstanceSim); const targets = [...this.option.closeEndPoints ?? [], ...this.option.errorEndPoints ?? [], ...this.option.requestEndPoints ?? [], ...this.option.filters ?? []]; Promise.all(targets.map((it) => typeof it === "function" ? this.simstanceManager.getOrNewSim({ target: it }) : it).map((it) => it.onInit(this))).then((it) => { this.startServer(); }); return this; } startServer() { if (this.option.serverOption && "key" in this.option.serverOption && "cert" in this.option.serverOption) { this.server = new import_https.Server(this.option.serverOption); const httpServer = new import_http.Server(); httpServer.on("request", (req, res) => { res.writeHead(301, { Location: `https://${req.headers.host}${req.url}` }); res.end(); }); httpServer.listen(80, this.option.listen.hostname, () => { console.log("HTTP redirect server running on port 80"); }); } else if (this.option.serverOption) { this.server = new import_http.Server(this.option.serverOption); } else { this.server = new import_http.Server(); } this.server.on("request", async (req, res) => { const transactionManager = this.option.transactionManagerFactory ? await this.option.transactionManagerFactory() : void 0; res.on("close", async () => { if (this.option.closeEndPoints) { for (const it of this.option.closeEndPoints) { try { const execute = typeof it === "function" ? this.simstanceManager.getOrNewSim({ target: it }) : it; const endPoint = execute?.endPoint(rr, this); if (endPoint instanceof Promise) { await endPoint; } } catch (e) { } } } if (!rr.resIsDone()) { rr.resEnd(); } }); res.on("error", async () => { if (this.option.errorEndPoints) { for (const it of this.option.errorEndPoints) { try { const execute = typeof it === "function" ? this.simstanceManager.getOrNewSim({ target: it }) : it; const endPoint = execute?.endPoint(rr, this); if (endPoint instanceof Promise) { await endPoint; } } catch (e) { } } } if (!rr.resIsDone()) { rr.resEnd(); } }); const rr = new import_RequestResponse.RequestResponse(req, res, { sessionManager: this.sessionManager, option: this.option }); rr.resSetHeader(import_HttpHeaders.HttpHeaders.Server, "simple-boot-http-server"); const cookie = rr.reqCookieGet(this.option.sessionOption.key); if (!cookie) { const session = await this.sessionManager.session(); rr.resSetHeader(import_HttpHeaders.HttpHeaders.SetCookie, `${this.option.sessionOption.key}=${session.uuid}; Path=/; HttpOnly`); } const otherStorage = /* @__PURE__ */ new Map(); otherStorage.set(import_RequestResponse.RequestResponse, rr); otherStorage.set(import_http.IncomingMessage, req); otherStorage.set(import_http.ServerResponse, res); try { transactionManager?.try(); if (this.option.requestEndPoints) { for (const it of this.option.requestEndPoints) { try { const execute = typeof it === "function" ? this.simstanceManager.getOrNewSim({ target: it }) : it; execute?.endPoint(rr, this); } catch (e) { } } } const filter = { carrier: /* @__PURE__ */ new Map(), filters: [] }; for (let i = 0; this.option.filters && i < this.option.filters.length; i++) { const it = this.option.filters[i]; const execute = typeof it === "function" ? this.simstanceManager.getOrNewSim({ target: it }) : it; let sw = true; if (execute?.proceedBefore) { sw = await execute.proceedBefore({ rr, app: this, carrier: filter.carrier }); filter.filters.push({ filter: execute, sw }); } if (!sw) { break; } } if (!rr.resIsDone()) { const routerModule = await super.routing(rr.reqIntent); otherStorage.set(import_RouterModule.RouterModule, routerModule); const moduleInstance = routerModule?.getModuleInstance?.(); let methods = []; if (routerModule && moduleInstance) { if (routerModule.propertyKeys) { const map = routerModule.propertyKeys?.map((it) => { return { propertyKey: it, config: (0, import_MethodMapping.getUrlMapping)(moduleInstance, it) }; }); methods.push(...map ?? []); } else { methods.push(...(0, import_MethodMapping.getUrlMappings)(moduleInstance).filter((it) => !(0, import_Router.getRoute)(moduleInstance, it.propertyKey)) ?? []); } if (rr.reqMethod()?.toUpperCase() === import_HttpMethod.HttpMethod.OPTIONS.toUpperCase()) { rr.resSetHeader(import_HttpHeaders.HttpHeaders.Allow, methods.map((it) => it.config.method).join(", ")); rr.resStatusCode(import_HttpStatus.HttpStatus.Ok); } methods = methods.filter((it) => it && it.propertyKey && it.config && rr.reqMethod()?.toUpperCase() === it.config.method.toUpperCase()); methods.sort((a, b) => { return (b.config?.req?.contentType?.length ?? 0) + (b.config?.req?.accept?.length ?? 0) - ((a.config?.req?.contentType?.length ?? 0) + (a.config?.req?.accept?.length ?? 0)); }); methods = methods.filter((it) => it.config?.req?.contentType ? !!it.config?.req?.contentType?.find((sit) => rr.reqHasContentTypeHeader(sit)) : true).filter((it) => it.config?.req?.accept ? !!it.config?.req?.accept?.find((sit) => rr.reqHasAcceptHeader(sit)) : true); if (methods[0]) { const it = methods[0]; const paramTypes = import_ReflectUtils.ReflectUtils.getParameterTypes(moduleInstance, it.propertyKey); const injects = (0, import_Inject.getInject)(moduleInstance, it.propertyKey); const validIndexs = (0, import_Validation.getValidIndex)(moduleInstance, it.propertyKey); if (injects) { const isJson = injects.find((it2) => it2.config?.situationType === import_MethodMapping.UrlMappingSituationType.REQ_JSON_BODY); const isFormUrl = injects.find((it2) => it2.config?.situationType === import_MethodMapping.UrlMappingSituationType.REQ_FORM_URL_BODY); const isTransactionManager = injects.find((it2) => it2.config?.situationType === import_InjectSituationType.InjectSituationType.TransactionManager); const siturationContainers = new import_Inject.SituationTypeContainers(); if (isJson) { let data2 = await rr.reqBodyJsonData(); if (isJson.type) { data2 = Object.assign(new isJson.type(), data2); } if (validIndexs.includes(isJson.index)) { const inValid = (0, import_Validation.execValidationInValid)(data2); if ((inValid?.length ?? 0) > 0) { throw new import_ValidException.ValidException(inValid); } } siturationContainers.push(new import_Inject.SituationTypeContainer({ situationType: import_MethodMapping.UrlMappingSituationType.REQ_JSON_BODY, data: data2 })); } if (isFormUrl) { let data2 = await rr.reqBodyFormUrlData(); if (isFormUrl.type) { data2 = Object.assign(new isFormUrl.type(), data2); } if (validIndexs.includes(isFormUrl.index)) { const inValid = (0, import_Validation.execValidationInValid)(data2); if ((inValid?.length ?? 0) > 0) { throw new import_ValidException.ValidException(inValid); } } siturationContainers.push(new import_Inject.SituationTypeContainer({ situationType: import_MethodMapping.UrlMappingSituationType.REQ_FORM_URL_BODY, data: data2 })); } if (isTransactionManager && isTransactionManager.type && transactionManager && transactionManager.hasTransaction(isTransactionManager.type)) { let data2 = await transactionManager.getTransaction(isTransactionManager.type); if (data2) { data2 = await data2.try(isTransactionManager.config.argument); siturationContainers.push(new import_Inject.SituationTypeContainer({ situationType: import_InjectSituationType.InjectSituationType.TransactionManager, data: data2, index: isTransactionManager.index })); } } if (siturationContainers.length) { otherStorage.set(import_Inject.SituationTypeContainers, siturationContainers); } } for (const paramType of paramTypes) { if (paramType === import_ReqFormUrlBody.ReqFormUrlBody) { otherStorage.set(import_ReqFormUrlBody.ReqFormUrlBody, await rr.reqBodyReqFormUrlBody()); } else if (paramType === import_ReqJsonBody.ReqJsonBody) { otherStorage.set(import_ReqJsonBody.ReqJsonBody, await rr.reqBodyReqJsonBody()); } else if (paramType === import_url.URLSearchParams) { otherStorage.set(import_url.URLSearchParams, rr.reqUrlSearchParams); } else if (paramType === import_ReqMultipartFormBody.ReqMultipartFormBody) { otherStorage.set(import_ReqMultipartFormBody.ReqMultipartFormBody, rr.reqBodyMultipartFormData()); } else if (paramType === import_ReqHeader.ReqHeader) { otherStorage.set(import_ReqHeader.ReqHeader, rr.reqHeaderObj); } } let data = await this.simstanceManager.executeBindParameterSimPromise({ target: moduleInstance, targetKey: it.propertyKey }, otherStorage); if (it.config?.resolver) { const execute = typeof it.config.resolver === "function" ? this.simstanceManager.getOrNewSim({ target: it.config.resolver }) : it.config.resolver; data = await execute?.resolve?.(data, rr); } const status = it.config?.res?.status ?? import_HttpStatus.HttpStatus.Ok; const headers = it.config?.res?.header ?? {}; if (it.config?.res?.contentType) { headers[import_HttpHeaders.HttpHeaders.ContentType] = it.config?.res?.contentType; } if ((it.config?.res?.contentType?.toLowerCase().indexOf(import_Mimes.Mimes.ApplicationJson.toLowerCase()) ?? -1) > -1) { data = JSON.stringify(data); } else if (data && typeof data === "object") { data = JSON.stringify(data); } rr.resSetHeaders(headers); rr.resSetStatusCode(status); rr.resWrite(data); } } if (this.option.noSuchRouteEndPointMappingThrow && methods.length <= 0 && rr.reqMethod()?.toUpperCase() !== import_HttpMethod.HttpMethod.OPTIONS) { throw this.option.noSuchRouteEndPointMappingThrow(rr); } } for (const it of filter.filters.reverse()) { if (it.filter?.proceedAfter && !await it.filter.proceedAfter({ rr, app: this, before: it.sw, carrier: filter.carrier })) { break; } } } catch (e) { transactionManager?.catch(e); rr.resStatusCode(e instanceof import_HttpError.HttpError ? e.status : import_HttpStatus.HttpStatus.InternalServerError); const execute = typeof this.option.globalAdvice === "function" ? this.simstanceManager.getOrNewSim(this.option.globalAdvice) : this.option.globalAdvice; if (!execute) { rr.resEnd(); return; } if (e && typeof e === "object") { otherStorage.set(e.constructor, e); otherStorage.set(import_Inject.SituationTypeContainer, new import_Inject.SituationTypeContainer({ situationType: import_ExceptionDecorator.ExceptionHandlerSituationType.ERROR_OBJECT, data: e })); } const target = (0, import_ExceptionDecorator.targetExceptionHandler)(execute, e); if (target) { await this.simstanceManager.executeBindParameterSimPromise({ target: execute, targetKey: target.propertyKey }, otherStorage); } } finally { transactionManager?.finally(); } if (!rr.resIsDone()) { rr.resEnd(); } }); this.server.listen(this.option.listen.port, this.option.listen.hostname, this.option.listen.backlog, () => { this.option.listen.listeningListener?.(this, this.server); }); } } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { SimpleBootHttpServer }); //# sourceMappingURL=SimpleBootHttpServer.js.map