@expressots/adapter-express 3.0.0-beta.4.2 → 4.0.0-preview.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -96
- package/lib/CHANGELOG.md +43 -0
- package/lib/README.md +39 -96
- package/lib/cjs/adapter-express/application-express.base.js +3 -1
- package/lib/cjs/adapter-express/application-express.js +1049 -85
- package/lib/cjs/adapter-express/express-utils/conditional-middleware.js +102 -0
- package/lib/cjs/adapter-express/express-utils/constants.js +17 -0
- package/lib/cjs/adapter-express/express-utils/content-negotiation-decorators.js +129 -0
- package/lib/cjs/adapter-express/express-utils/decorators.js +186 -49
- package/lib/cjs/adapter-express/express-utils/exception-filter-decorators.js +11 -0
- package/lib/cjs/adapter-express/express-utils/guard-context-factory.js +84 -0
- package/lib/cjs/adapter-express/express-utils/guard-middleware.js +115 -0
- package/lib/cjs/adapter-express/express-utils/guard-utils.js +18 -0
- package/lib/cjs/adapter-express/express-utils/http-context-store.js +15 -0
- package/lib/cjs/adapter-express/express-utils/http-status-middleware.js +37 -2
- package/lib/cjs/adapter-express/express-utils/index.js +67 -1
- package/lib/cjs/adapter-express/express-utils/interceptor-middleware.js +132 -0
- package/lib/cjs/adapter-express/express-utils/inversify-express-server.js +810 -63
- package/lib/cjs/adapter-express/express-utils/lazy-module-middleware.js +241 -0
- package/lib/cjs/adapter-express/express-utils/middleware-composition.js +95 -0
- package/lib/cjs/adapter-express/express-utils/permission-preloader.middleware.js +48 -0
- package/lib/cjs/adapter-express/express-utils/route-constraints.js +95 -0
- package/lib/cjs/adapter-express/express-utils/scope-extractor.interface.js +2 -0
- package/lib/cjs/adapter-express/express-utils/scope-extractor.js +66 -0
- package/lib/cjs/adapter-express/express-utils/setup-authorization.js +71 -0
- package/lib/cjs/adapter-express/express-utils/setup-event-system.js +113 -0
- package/lib/cjs/adapter-express/express-utils/setup-interceptors.js +103 -0
- package/lib/cjs/adapter-express/express-utils/setup-lazy-loading.js +228 -0
- package/lib/cjs/adapter-express/express-utils/utils.js +30 -12
- package/lib/cjs/adapter-express/express-utils/validation-decorators.js +205 -0
- package/lib/cjs/adapter-express/express-utils/validation-service.js +252 -0
- package/lib/cjs/adapter-express/index.js +7 -5
- package/lib/cjs/adapter-express/micro-api/application-express-micro-route.js +31 -1
- package/lib/cjs/adapter-express/micro-api/application-express-micro.js +11 -37
- package/lib/cjs/adapter-express/micro-api/gateway/circuit-breaker.js +174 -0
- package/lib/cjs/adapter-express/micro-api/gateway/index.js +11 -0
- package/lib/cjs/adapter-express/micro-api/gateway/service-proxy.js +214 -0
- package/lib/cjs/adapter-express/micro-api/index.js +27 -3
- package/lib/cjs/adapter-express/micro-api/micro.js +217 -0
- package/lib/cjs/adapter-express/micro-api/queue/index.js +8 -0
- package/lib/cjs/adapter-express/micro-api/queue/queue.interface.js +2 -0
- package/lib/cjs/adapter-express/micro-api/queue/rabbitmq-consumer.js +255 -0
- package/lib/cjs/adapter-express/micro-api/serverless/aws-lambda.adapter.js +183 -0
- package/lib/cjs/adapter-express/micro-api/serverless/cloudflare.adapter.js +158 -0
- package/lib/cjs/adapter-express/micro-api/serverless/index.js +12 -0
- package/lib/cjs/adapter-express/micro-api/serverless/vercel.adapter.js +102 -0
- package/lib/cjs/adapter-express/micro-api/service-mesh/index.js +10 -0
- package/lib/cjs/adapter-express/micro-api/service-mesh/service-client.js +194 -0
- package/lib/cjs/adapter-express/micro-api/service-mesh/service-discovery.js +261 -0
- package/lib/cjs/adapter-express/middleware/index.js +21 -0
- package/lib/cjs/adapter-express/middleware/request-logging.middleware.js +244 -0
- package/lib/cjs/adapter-express/render/engine.js +15 -15
- package/lib/cjs/adapter-express/render/index.js +5 -0
- package/lib/cjs/adapter-express/studio/index.js +9 -0
- package/lib/cjs/adapter-express/studio/studio-integration.js +214 -0
- package/lib/cjs/index.js +1 -1
- package/lib/cjs/types/adapter-express/application-express.base.d.ts +20 -7
- package/lib/cjs/types/adapter-express/application-express.d.ts +273 -32
- package/lib/cjs/types/adapter-express/express-utils/base-middleware.d.ts +2 -2
- package/lib/cjs/types/adapter-express/express-utils/conditional-middleware.d.ts +97 -0
- package/lib/cjs/types/adapter-express/express-utils/constants.d.ts +13 -0
- package/lib/cjs/types/adapter-express/express-utils/content-negotiation-decorators.d.ts +94 -0
- package/lib/cjs/types/adapter-express/express-utils/decorators.d.ts +54 -6
- package/lib/cjs/types/adapter-express/express-utils/exception-filter-decorators.d.ts +6 -0
- package/lib/cjs/types/adapter-express/express-utils/guard-context-factory.d.ts +17 -0
- package/lib/cjs/types/adapter-express/express-utils/guard-middleware.d.ts +22 -0
- package/lib/cjs/types/adapter-express/express-utils/guard-utils.d.ts +11 -0
- package/lib/cjs/types/adapter-express/express-utils/http-context-store.d.ts +20 -0
- package/lib/cjs/types/adapter-express/express-utils/httpResponseMessage.d.ts +1 -1
- package/lib/cjs/types/adapter-express/express-utils/index.d.ts +30 -2
- package/lib/cjs/types/adapter-express/express-utils/interceptor-middleware.d.ts +40 -0
- package/lib/cjs/types/adapter-express/express-utils/interfaces.d.ts +42 -5
- package/lib/cjs/types/adapter-express/express-utils/inversify-express-server.d.ts +114 -2
- package/lib/cjs/types/adapter-express/express-utils/lazy-module-middleware.d.ts +122 -0
- package/lib/cjs/types/adapter-express/express-utils/middleware-composition.d.ts +85 -0
- package/lib/cjs/types/adapter-express/express-utils/permission-preloader.middleware.d.ts +10 -0
- package/lib/cjs/types/adapter-express/express-utils/route-constraints.d.ts +89 -0
- package/lib/cjs/types/adapter-express/express-utils/scope-extractor.d.ts +21 -0
- package/lib/cjs/types/adapter-express/express-utils/scope-extractor.interface.d.ts +12 -0
- package/lib/cjs/types/adapter-express/express-utils/setup-authorization.d.ts +34 -0
- package/lib/cjs/types/adapter-express/express-utils/setup-event-system.d.ts +118 -0
- package/lib/cjs/types/adapter-express/express-utils/setup-interceptors.d.ts +115 -0
- package/lib/cjs/types/adapter-express/express-utils/setup-lazy-loading.d.ts +123 -0
- package/lib/cjs/types/adapter-express/express-utils/utils.d.ts +17 -2
- package/lib/cjs/types/adapter-express/express-utils/validation-decorators.d.ts +145 -0
- package/lib/cjs/types/adapter-express/express-utils/validation-service.d.ts +88 -0
- package/lib/cjs/types/adapter-express/index.d.ts +6 -4
- package/lib/cjs/types/adapter-express/micro-api/application-express-micro-route.d.ts +25 -14
- package/lib/cjs/types/adapter-express/micro-api/application-express-micro.d.ts +3 -10
- package/lib/cjs/types/adapter-express/micro-api/gateway/circuit-breaker.d.ts +111 -0
- package/lib/cjs/types/adapter-express/micro-api/gateway/index.d.ts +5 -0
- package/lib/cjs/types/adapter-express/micro-api/gateway/service-proxy.d.ts +83 -0
- package/lib/cjs/types/adapter-express/micro-api/index.d.ts +7 -1
- package/lib/cjs/types/adapter-express/micro-api/micro.d.ts +66 -0
- package/lib/cjs/types/adapter-express/micro-api/queue/index.d.ts +5 -0
- package/lib/cjs/types/adapter-express/micro-api/queue/queue.interface.d.ts +60 -0
- package/lib/cjs/types/adapter-express/micro-api/queue/rabbitmq-consumer.d.ts +86 -0
- package/lib/cjs/types/adapter-express/micro-api/serverless/aws-lambda.adapter.d.ts +77 -0
- package/lib/cjs/types/adapter-express/micro-api/serverless/cloudflare.adapter.d.ts +64 -0
- package/lib/cjs/types/adapter-express/micro-api/serverless/index.d.ts +6 -0
- package/lib/cjs/types/adapter-express/micro-api/serverless/vercel.adapter.d.ts +56 -0
- package/lib/cjs/types/adapter-express/micro-api/service-mesh/index.d.ts +5 -0
- package/lib/cjs/types/adapter-express/micro-api/service-mesh/service-client.d.ts +122 -0
- package/lib/cjs/types/adapter-express/micro-api/service-mesh/service-discovery.d.ts +150 -0
- package/lib/cjs/types/adapter-express/middleware/index.d.ts +5 -0
- package/lib/cjs/types/adapter-express/middleware/request-logging.middleware.d.ts +65 -0
- package/lib/cjs/types/adapter-express/render/index.d.ts +1 -0
- package/lib/cjs/types/adapter-express/studio/index.d.ts +1 -0
- package/lib/cjs/types/adapter-express/studio/studio-integration.d.ts +92 -0
- package/lib/cjs/types/index.d.ts +1 -1
- package/lib/esm/adapter-express/application-express.base.js +24 -0
- package/lib/esm/adapter-express/application-express.js +1300 -0
- package/lib/esm/adapter-express/application-express.types.js +1 -0
- package/lib/esm/adapter-express/express-utils/base-middleware.js +19 -0
- package/lib/esm/adapter-express/express-utils/conditional-middleware.js +96 -0
- package/lib/esm/adapter-express/express-utils/constants.js +63 -0
- package/lib/esm/adapter-express/express-utils/content/httpContent.js +6 -0
- package/lib/esm/adapter-express/express-utils/content-negotiation-decorators.js +120 -0
- package/lib/esm/adapter-express/express-utils/decorators.js +575 -0
- package/lib/esm/adapter-express/express-utils/exception-filter-decorators.js +6 -0
- package/lib/esm/adapter-express/express-utils/guard-context-factory.js +83 -0
- package/lib/esm/adapter-express/express-utils/guard-middleware.js +115 -0
- package/lib/esm/adapter-express/express-utils/guard-utils.js +14 -0
- package/lib/esm/adapter-express/express-utils/http-context-store.js +10 -0
- package/lib/esm/adapter-express/express-utils/http-status-middleware.js +116 -0
- package/lib/esm/adapter-express/express-utils/httpResponseMessage.js +29 -0
- package/lib/esm/adapter-express/express-utils/index.js +24 -0
- package/lib/esm/adapter-express/express-utils/interceptor-middleware.js +130 -0
- package/lib/esm/adapter-express/express-utils/interfaces.js +1 -0
- package/lib/esm/adapter-express/express-utils/inversify-express-server.js +1031 -0
- package/lib/esm/adapter-express/express-utils/lazy-module-middleware.js +236 -0
- package/lib/esm/adapter-express/express-utils/middleware-composition.js +89 -0
- package/lib/esm/adapter-express/express-utils/permission-preloader.middleware.js +45 -0
- package/lib/esm/adapter-express/express-utils/resolver-multer.js +30 -0
- package/lib/esm/adapter-express/express-utils/route-constraints.js +91 -0
- package/lib/esm/adapter-express/express-utils/scope-extractor.interface.js +1 -0
- package/lib/esm/adapter-express/express-utils/scope-extractor.js +63 -0
- package/lib/esm/adapter-express/express-utils/setup-authorization.js +68 -0
- package/lib/esm/adapter-express/express-utils/setup-event-system.js +110 -0
- package/lib/esm/adapter-express/express-utils/setup-interceptors.js +100 -0
- package/lib/esm/adapter-express/express-utils/setup-lazy-loading.js +225 -0
- package/lib/esm/adapter-express/express-utils/utils.js +68 -0
- package/lib/esm/adapter-express/express-utils/validation-decorators.js +199 -0
- package/lib/esm/adapter-express/express-utils/validation-service.js +251 -0
- package/lib/esm/adapter-express/index.js +7 -0
- package/lib/esm/adapter-express/micro-api/application-express-micro-container.js +48 -0
- package/lib/esm/adapter-express/micro-api/application-express-micro-route.js +128 -0
- package/lib/esm/adapter-express/micro-api/application-express-micro.js +161 -0
- package/lib/esm/adapter-express/micro-api/gateway/circuit-breaker.js +174 -0
- package/lib/esm/adapter-express/micro-api/gateway/index.js +5 -0
- package/lib/esm/adapter-express/micro-api/gateway/service-proxy.js +210 -0
- package/lib/esm/adapter-express/micro-api/index.js +10 -0
- package/lib/esm/adapter-express/micro-api/micro.js +211 -0
- package/lib/esm/adapter-express/micro-api/queue/index.js +4 -0
- package/lib/esm/adapter-express/micro-api/queue/queue.interface.js +1 -0
- package/lib/esm/adapter-express/micro-api/queue/rabbitmq-consumer.js +229 -0
- package/lib/esm/adapter-express/micro-api/serverless/aws-lambda.adapter.js +180 -0
- package/lib/esm/adapter-express/micro-api/serverless/cloudflare.adapter.js +155 -0
- package/lib/esm/adapter-express/micro-api/serverless/index.js +6 -0
- package/lib/esm/adapter-express/micro-api/serverless/vercel.adapter.js +99 -0
- package/lib/esm/adapter-express/micro-api/service-mesh/index.js +5 -0
- package/lib/esm/adapter-express/micro-api/service-mesh/service-client.js +191 -0
- package/lib/esm/adapter-express/micro-api/service-mesh/service-discovery.js +259 -0
- package/lib/esm/adapter-express/middleware/index.js +5 -0
- package/lib/esm/adapter-express/middleware/request-logging.middleware.js +239 -0
- package/lib/esm/adapter-express/render/constants.js +37 -0
- package/lib/esm/adapter-express/render/engine.js +51 -0
- package/lib/esm/adapter-express/render/index.js +1 -0
- package/lib/esm/adapter-express/render/resolve-render.js +30 -0
- package/lib/esm/adapter-express/studio/index.js +1 -0
- package/lib/esm/adapter-express/studio/studio-integration.js +184 -0
- package/lib/esm/index.mjs +1 -0
- package/lib/esm/package.json +3 -0
- package/lib/esm/types/adapter-express/application-express.base.d.ts +77 -0
- package/lib/esm/types/adapter-express/application-express.d.ts +411 -0
- package/lib/esm/types/adapter-express/application-express.types.d.ts +23 -0
- package/lib/esm/types/adapter-express/express-utils/base-middleware.d.ts +8 -0
- package/lib/esm/types/adapter-express/express-utils/conditional-middleware.d.ts +97 -0
- package/lib/esm/types/adapter-express/express-utils/constants.d.ts +57 -0
- package/lib/esm/types/adapter-express/express-utils/content/httpContent.d.ts +6 -0
- package/lib/esm/types/adapter-express/express-utils/content-negotiation-decorators.d.ts +94 -0
- package/lib/esm/types/adapter-express/express-utils/decorators.d.ts +257 -0
- package/lib/esm/types/adapter-express/express-utils/exception-filter-decorators.d.ts +6 -0
- package/lib/esm/types/adapter-express/express-utils/guard-context-factory.d.ts +17 -0
- package/lib/esm/types/adapter-express/express-utils/guard-middleware.d.ts +22 -0
- package/lib/esm/types/adapter-express/express-utils/guard-utils.d.ts +11 -0
- package/lib/esm/types/adapter-express/express-utils/http-context-store.d.ts +20 -0
- package/lib/esm/types/adapter-express/express-utils/http-status-middleware.d.ts +26 -0
- package/lib/esm/types/adapter-express/express-utils/httpResponseMessage.d.ts +14 -0
- package/lib/esm/types/adapter-express/express-utils/index.d.ts +30 -0
- package/lib/esm/types/adapter-express/express-utils/interceptor-middleware.d.ts +40 -0
- package/lib/esm/types/adapter-express/express-utils/interfaces.d.ts +115 -0
- package/lib/esm/types/adapter-express/express-utils/inversify-express-server.d.ts +172 -0
- package/lib/esm/types/adapter-express/express-utils/lazy-module-middleware.d.ts +122 -0
- package/lib/esm/types/adapter-express/express-utils/middleware-composition.d.ts +85 -0
- package/lib/esm/types/adapter-express/express-utils/permission-preloader.middleware.d.ts +10 -0
- package/lib/esm/types/adapter-express/express-utils/resolver-multer.d.ts +7 -0
- package/lib/esm/types/adapter-express/express-utils/route-constraints.d.ts +89 -0
- package/lib/esm/types/adapter-express/express-utils/scope-extractor.d.ts +21 -0
- package/lib/esm/types/adapter-express/express-utils/scope-extractor.interface.d.ts +12 -0
- package/lib/esm/types/adapter-express/express-utils/setup-authorization.d.ts +34 -0
- package/lib/esm/types/adapter-express/express-utils/setup-event-system.d.ts +118 -0
- package/lib/esm/types/adapter-express/express-utils/setup-interceptors.d.ts +115 -0
- package/lib/esm/types/adapter-express/express-utils/setup-lazy-loading.d.ts +123 -0
- package/lib/esm/types/adapter-express/express-utils/utils.d.ts +24 -0
- package/lib/esm/types/adapter-express/express-utils/validation-decorators.d.ts +145 -0
- package/lib/esm/types/adapter-express/express-utils/validation-service.d.ts +88 -0
- package/lib/esm/types/adapter-express/index.d.ts +7 -0
- package/lib/esm/types/adapter-express/micro-api/application-express-micro-container.d.ts +47 -0
- package/lib/esm/types/adapter-express/micro-api/application-express-micro-route.d.ts +104 -0
- package/lib/esm/types/adapter-express/micro-api/application-express-micro.d.ts +72 -0
- package/lib/esm/types/adapter-express/micro-api/gateway/circuit-breaker.d.ts +111 -0
- package/lib/esm/types/adapter-express/micro-api/gateway/index.d.ts +5 -0
- package/lib/esm/types/adapter-express/micro-api/gateway/service-proxy.d.ts +83 -0
- package/lib/esm/types/adapter-express/micro-api/index.d.ts +7 -0
- package/lib/esm/types/adapter-express/micro-api/micro.d.ts +66 -0
- package/lib/esm/types/adapter-express/micro-api/queue/index.d.ts +5 -0
- package/lib/esm/types/adapter-express/micro-api/queue/queue.interface.d.ts +60 -0
- package/lib/esm/types/adapter-express/micro-api/queue/rabbitmq-consumer.d.ts +86 -0
- package/lib/esm/types/adapter-express/micro-api/serverless/aws-lambda.adapter.d.ts +77 -0
- package/lib/esm/types/adapter-express/micro-api/serverless/cloudflare.adapter.d.ts +64 -0
- package/lib/esm/types/adapter-express/micro-api/serverless/index.d.ts +6 -0
- package/lib/esm/types/adapter-express/micro-api/serverless/vercel.adapter.d.ts +56 -0
- package/lib/esm/types/adapter-express/micro-api/service-mesh/index.d.ts +5 -0
- package/lib/esm/types/adapter-express/micro-api/service-mesh/service-client.d.ts +122 -0
- package/lib/esm/types/adapter-express/micro-api/service-mesh/service-discovery.d.ts +150 -0
- package/lib/esm/types/adapter-express/middleware/index.d.ts +5 -0
- package/lib/esm/types/adapter-express/middleware/request-logging.middleware.d.ts +65 -0
- package/lib/esm/types/adapter-express/render/constants.d.ts +26 -0
- package/lib/esm/types/adapter-express/render/engine.d.ts +20 -0
- package/lib/esm/types/adapter-express/render/index.d.ts +5 -0
- package/lib/esm/types/adapter-express/render/resolve-render.d.ts +7 -0
- package/lib/esm/types/adapter-express/studio/index.d.ts +1 -0
- package/lib/esm/types/adapter-express/studio/studio-integration.d.ts +92 -0
- package/lib/esm/types/index.d.ts +1 -0
- package/lib/package.json +156 -146
- package/package.json +156 -146
- package/lib/cjs/di/di.interfaces.js +0 -10
- package/lib/cjs/types/di/di.interfaces.d.ts +0 -289
|
@@ -0,0 +1,1031 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-unused-vars */
|
|
2
|
+
import express, { Router, } from "express";
|
|
3
|
+
import { GuardExecutor, ContextManager, findFlowTracker, NotFoundError, InterceptorExecutor, InterceptorRegistry, INTERCEPTOR_METADATA_KEY, Logger, getErrorHints, getDefaultSuggestionsConfig, formatSuggestions, } from "@expressots/core";
|
|
4
|
+
import { GuardContextFactory } from "./guard-context-factory.js";
|
|
5
|
+
import { BaseMiddleware } from "./base-middleware.js";
|
|
6
|
+
import { getControllersFromMetadata, getControllersFromContainer, getControllerMetadata, getControllerMethodMetadata, getControllerParameterMetadata, instanceOfIHttpActionResult, getContentNegotiationMetadata, } from "./utils.js";
|
|
7
|
+
import { getValidationMetadata } from "./validation-decorators.js";
|
|
8
|
+
import { TYPE, DEFAULT_ROUTING_ROOT_PATH, PARAMETER_TYPE, DUPLICATED_CONTROLLER_NAME, } from "./constants.js";
|
|
9
|
+
import { HttpResponseMessage } from "./httpResponseMessage.js";
|
|
10
|
+
import { getRenderMetadata } from "./decorators.js";
|
|
11
|
+
import { isConditionalMiddleware, } from "./conditional-middleware.js";
|
|
12
|
+
import { isComposedMiddleware } from "./middleware-composition.js";
|
|
13
|
+
import { getControllerGuards, getMethodGuards } from "./guard-utils.js";
|
|
14
|
+
import { GuardMiddleware } from "./guard-middleware.js";
|
|
15
|
+
import { InterceptorMiddleware, createInterceptorMiddleware } from "./interceptor-middleware.js";
|
|
16
|
+
import { getHttpContext, setHttpContext } from "./http-context-store.js";
|
|
17
|
+
// Lazy-load route registry from @expressots/core. Static import because
|
|
18
|
+
// `getRouteRegistry` is part of the core's public surface; we just guard
|
|
19
|
+
// against it being undefined to keep this non-critical (suggestions are
|
|
20
|
+
// optional).
|
|
21
|
+
import { getRouteRegistry as coreGetRouteRegistry } from "@expressots/core";
|
|
22
|
+
function getRouteRegistryModule() {
|
|
23
|
+
if (typeof coreGetRouteRegistry !== "function")
|
|
24
|
+
return null;
|
|
25
|
+
return { getRouteRegistry: coreGetRouteRegistry };
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Properly join route path segments, handling:
|
|
29
|
+
* - Controller "/" + method "/users" = "/users"
|
|
30
|
+
* - Controller "/api" + method "users" = "/api/users"
|
|
31
|
+
* - Controller "/api/" + method "/users" = "/api/users"
|
|
32
|
+
* - Controller "/" + method "/" = "/"
|
|
33
|
+
*/
|
|
34
|
+
function joinRoutePaths(...segments) {
|
|
35
|
+
const parts = [];
|
|
36
|
+
for (const segment of segments) {
|
|
37
|
+
if (!segment || segment === "")
|
|
38
|
+
continue;
|
|
39
|
+
// For root path only, skip if we have parts
|
|
40
|
+
if (segment === "/" && parts.length > 0)
|
|
41
|
+
continue;
|
|
42
|
+
// Remove trailing slash
|
|
43
|
+
let cleaned = segment.endsWith("/") && segment.length > 1 ? segment.slice(0, -1) : segment;
|
|
44
|
+
// Handle leading slash
|
|
45
|
+
if (parts.length > 0) {
|
|
46
|
+
// Ensure leading slash for non-first segments
|
|
47
|
+
cleaned = cleaned.startsWith("/") ? cleaned : `/${cleaned}`;
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
// First segment - ensure starts with /
|
|
51
|
+
cleaned = cleaned.startsWith("/") ? cleaned : `/${cleaned}`;
|
|
52
|
+
}
|
|
53
|
+
if (cleaned && cleaned !== "/") {
|
|
54
|
+
parts.push(cleaned);
|
|
55
|
+
}
|
|
56
|
+
else if (parts.length === 0) {
|
|
57
|
+
parts.push("/");
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (parts.length === 0)
|
|
61
|
+
return "/";
|
|
62
|
+
// Join and normalize double slashes
|
|
63
|
+
return parts.join("").replace(/\/+/g, "/");
|
|
64
|
+
}
|
|
65
|
+
export class InversifyExpressServer {
|
|
66
|
+
_router;
|
|
67
|
+
_container;
|
|
68
|
+
_app;
|
|
69
|
+
_configFn;
|
|
70
|
+
_errorConfigFn;
|
|
71
|
+
_routingConfig;
|
|
72
|
+
_AuthProvider;
|
|
73
|
+
_forceControllers;
|
|
74
|
+
_contentNegotiationService;
|
|
75
|
+
_validationService;
|
|
76
|
+
/**
|
|
77
|
+
* Wrapper for the express server.
|
|
78
|
+
*
|
|
79
|
+
* @param container Container loaded with all controllers and their dependencies.
|
|
80
|
+
* @param customRouter optional express.Router custom router
|
|
81
|
+
* @param routingConfig optional interfaces.RoutingConfig routing config
|
|
82
|
+
* @param customApp optional express.Application custom app
|
|
83
|
+
* @param authProvider optional interfaces.AuthProvider auth provider
|
|
84
|
+
* @param forceControllers optional boolean setting to force controllers (defaults do true)
|
|
85
|
+
*/
|
|
86
|
+
constructor(container, customRouter, routingConfig, customApp, authProvider, forceControllers = true) {
|
|
87
|
+
this._container = container;
|
|
88
|
+
this._forceControllers = forceControllers;
|
|
89
|
+
this._router = customRouter || Router();
|
|
90
|
+
this._routingConfig = routingConfig || {
|
|
91
|
+
rootPath: DEFAULT_ROUTING_ROOT_PATH,
|
|
92
|
+
};
|
|
93
|
+
this._app = customApp || express();
|
|
94
|
+
if (authProvider) {
|
|
95
|
+
this._AuthProvider = authProvider;
|
|
96
|
+
container.bind(TYPE.AuthProvider).to(this._AuthProvider);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Sets the configuration function to be applied to the application.
|
|
101
|
+
* Note that the config function is not actually executed until a call to
|
|
102
|
+
* InversifyExpresServer.build().
|
|
103
|
+
*
|
|
104
|
+
* This method is chainable.
|
|
105
|
+
*
|
|
106
|
+
* @param fn Function in which app-level middleware can be registered.
|
|
107
|
+
*/
|
|
108
|
+
setConfig(fn) {
|
|
109
|
+
this._configFn = fn;
|
|
110
|
+
return this;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Sets the error handler configuration function to be applied to the application.
|
|
114
|
+
* Note that the error config function is not actually executed until a call to
|
|
115
|
+
* InversifyExpressServer.build().
|
|
116
|
+
*
|
|
117
|
+
* This method is chainable.
|
|
118
|
+
*
|
|
119
|
+
* @param fn Function in which app-level error handlers can be registered.
|
|
120
|
+
*/
|
|
121
|
+
setErrorConfig(fn) {
|
|
122
|
+
this._errorConfigFn = fn;
|
|
123
|
+
return this;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Applies all routes and configuration to the server, returning the express application.
|
|
127
|
+
*/
|
|
128
|
+
build() {
|
|
129
|
+
// The very first middleware to be invoked: create an HttpContext per
|
|
130
|
+
// request and attach it via a WeakMap (see ./http-context-store).
|
|
131
|
+
// This is cheaper than the previous `Reflect.defineMetadata` call
|
|
132
|
+
// because it bypasses reflect-metadata's string-keyed map.
|
|
133
|
+
this._app.all("*", (req, res, next) => {
|
|
134
|
+
this._createHttpContext(req, res, next)
|
|
135
|
+
.then((httpContext) => {
|
|
136
|
+
setHttpContext(req, httpContext);
|
|
137
|
+
next();
|
|
138
|
+
})
|
|
139
|
+
.catch(next);
|
|
140
|
+
});
|
|
141
|
+
// register server-level middleware before anything else
|
|
142
|
+
if (this._configFn) {
|
|
143
|
+
this._configFn.apply(undefined, [this._app]);
|
|
144
|
+
}
|
|
145
|
+
this.registerControllers();
|
|
146
|
+
this.registerNotFoundHandler();
|
|
147
|
+
// register error handlers after controllers
|
|
148
|
+
if (this._errorConfigFn) {
|
|
149
|
+
this._errorConfigFn.apply(undefined, [this._app]);
|
|
150
|
+
}
|
|
151
|
+
return this._app;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Install a catch-all 404 handler that runs after every registered route.
|
|
155
|
+
*
|
|
156
|
+
* When the user has the suggestions feature enabled (default in development),
|
|
157
|
+
* this consults the route registry, computes "Did you mean ...?" suggestions
|
|
158
|
+
* via `getErrorHints` from `@expressots/core`, logs them through the framework
|
|
159
|
+
* Logger, and returns a structured RFC-7807-style JSON 404 instead of the
|
|
160
|
+
* default Express HTML.
|
|
161
|
+
*
|
|
162
|
+
* Users who want the legacy Express HTML 404 can opt out by configuring the
|
|
163
|
+
* Logger with `suggestions.enabled = false` (this also disables the JSON
|
|
164
|
+
* envelope so they can install their own 404 handler in the error-config fn).
|
|
165
|
+
*
|
|
166
|
+
* @private
|
|
167
|
+
*/
|
|
168
|
+
registerNotFoundHandler() {
|
|
169
|
+
this._app.use((req, res, next) => {
|
|
170
|
+
if (res.headersSent) {
|
|
171
|
+
return next();
|
|
172
|
+
}
|
|
173
|
+
const suggestionsConfig = this.resolveSuggestionsConfig();
|
|
174
|
+
if (!suggestionsConfig.enabled) {
|
|
175
|
+
return next();
|
|
176
|
+
}
|
|
177
|
+
const requestedPath = req.originalUrl || req.url;
|
|
178
|
+
const requestedMethod = req.method;
|
|
179
|
+
const hints = getErrorHints(new Error(`Route '${requestedMethod} ${requestedPath}' not found`), {
|
|
180
|
+
path: requestedPath,
|
|
181
|
+
method: requestedMethod,
|
|
182
|
+
statusCode: 404,
|
|
183
|
+
}, suggestionsConfig);
|
|
184
|
+
if (hints.length > 0) {
|
|
185
|
+
try {
|
|
186
|
+
const formatted = formatSuggestions(hints);
|
|
187
|
+
if (formatted) {
|
|
188
|
+
const logger = this.resolveLogger();
|
|
189
|
+
if (logger) {
|
|
190
|
+
logger.warn(`Route not found: ${requestedMethod} ${requestedPath}${formatted}`, "router-404");
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
// eslint-disable-next-line no-console
|
|
194
|
+
console.warn(`[router-404] Route not found: ${requestedMethod} ${requestedPath}${formatted}`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
// Suggestion logging is best-effort; never fail the request because of it.
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const routeSuggestion = hints.find((hint) => hint.type === "route");
|
|
203
|
+
const actionHint = hints.find((hint) => hint.type === "hint");
|
|
204
|
+
const body = {
|
|
205
|
+
type: "https://expressots.dev/errors/not-found",
|
|
206
|
+
title: "Route Not Found",
|
|
207
|
+
status: 404,
|
|
208
|
+
detail: `Route '${requestedMethod} ${requestedPath}' does not exist`,
|
|
209
|
+
instance: requestedPath,
|
|
210
|
+
timestamp: new Date().toISOString(),
|
|
211
|
+
};
|
|
212
|
+
if (routeSuggestion?.routes && routeSuggestion.routes.length > 0) {
|
|
213
|
+
body.suggestions = routeSuggestion.routes.map((suggestion) => ({
|
|
214
|
+
method: suggestion.route.method,
|
|
215
|
+
path: suggestion.route.fullPath || suggestion.route.path,
|
|
216
|
+
similarity: Math.round(suggestion.similarity * 100),
|
|
217
|
+
reason: suggestion.reason,
|
|
218
|
+
}));
|
|
219
|
+
}
|
|
220
|
+
else if (actionHint?.actions && actionHint.actions.length > 0) {
|
|
221
|
+
body.actions = actionHint.actions;
|
|
222
|
+
}
|
|
223
|
+
res.status(404).type("application/json").send(JSON.stringify(body));
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Resolve the user-configured suggestions config, falling back to the
|
|
228
|
+
* env-aware default when the Logger is not bound or has no overrides.
|
|
229
|
+
*
|
|
230
|
+
* @private
|
|
231
|
+
*/
|
|
232
|
+
resolveSuggestionsConfig() {
|
|
233
|
+
const fallback = getDefaultSuggestionsConfig();
|
|
234
|
+
const logger = this.resolveLogger();
|
|
235
|
+
if (!logger) {
|
|
236
|
+
return fallback;
|
|
237
|
+
}
|
|
238
|
+
try {
|
|
239
|
+
const loggerConfig = logger.getConfig?.();
|
|
240
|
+
if (loggerConfig?.suggestions) {
|
|
241
|
+
return { ...fallback, ...loggerConfig.suggestions };
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
// Logger may not expose getConfig in older versions; fall through.
|
|
246
|
+
}
|
|
247
|
+
return fallback;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Resolve the framework Logger from DI when available.
|
|
251
|
+
*
|
|
252
|
+
* @private
|
|
253
|
+
*/
|
|
254
|
+
resolveLogger() {
|
|
255
|
+
try {
|
|
256
|
+
// The `Logger` symbol is the constructor itself in our DI bindings.
|
|
257
|
+
if (this._container.isBound(Logger)) {
|
|
258
|
+
return this._container.get(Logger);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
// not bound yet
|
|
263
|
+
}
|
|
264
|
+
return undefined;
|
|
265
|
+
}
|
|
266
|
+
registerControllers() {
|
|
267
|
+
// Fake HttpContext is needed during registration
|
|
268
|
+
this._container.bind(TYPE.HttpContext).toConstantValue({});
|
|
269
|
+
// Initialize interceptor system if not already bound
|
|
270
|
+
this.initializeInterceptorSystem();
|
|
271
|
+
const constructors = getControllersFromMetadata();
|
|
272
|
+
constructors.forEach((constructor) => {
|
|
273
|
+
const { name } = constructor;
|
|
274
|
+
if (this._container.isBoundNamed(TYPE.Controller, name)) {
|
|
275
|
+
throw new Error(DUPLICATED_CONTROLLER_NAME(name));
|
|
276
|
+
}
|
|
277
|
+
this._container
|
|
278
|
+
.bind(TYPE.Controller)
|
|
279
|
+
.to(constructor)
|
|
280
|
+
.whenTargetNamed(name);
|
|
281
|
+
});
|
|
282
|
+
const controllers = getControllersFromContainer(this._container, this._forceControllers);
|
|
283
|
+
controllers.forEach((controller) => {
|
|
284
|
+
const controllerMetadata = getControllerMetadata(controller.constructor);
|
|
285
|
+
const methodMetadata = getControllerMethodMetadata(controller.constructor);
|
|
286
|
+
const parameterMetadata = getControllerParameterMetadata(controller.constructor);
|
|
287
|
+
if (controllerMetadata && methodMetadata) {
|
|
288
|
+
const controllerMiddleware = this.resolveMiddleware(...controllerMetadata.middleware);
|
|
289
|
+
methodMetadata.forEach((metadata) => {
|
|
290
|
+
let paramList = [];
|
|
291
|
+
if (parameterMetadata) {
|
|
292
|
+
paramList = parameterMetadata[metadata.key] || [];
|
|
293
|
+
}
|
|
294
|
+
// Create base handler
|
|
295
|
+
let handler = this.handlerFactory(controllerMetadata.target.name, metadata.key, paramList, controller.constructor, // Pass controller constructor for metadata
|
|
296
|
+
metadata);
|
|
297
|
+
// Wrap handler with interceptor middleware if interceptors are defined
|
|
298
|
+
const interceptors = this.extractInterceptors(controller.constructor, metadata.key);
|
|
299
|
+
if (interceptors.length > 0 && this.isInterceptorSystemReady()) {
|
|
300
|
+
handler = this.wrapWithInterceptors(handler, controller.constructor, metadata.key);
|
|
301
|
+
}
|
|
302
|
+
const routeMiddleware = this.resolveMiddleware(...metadata.middleware);
|
|
303
|
+
// Determine version: method-level version overrides controller-level version
|
|
304
|
+
const version = metadata.version || controllerMetadata.version;
|
|
305
|
+
const versionPrefix = version ? `/${version}` : "";
|
|
306
|
+
// Properly join paths to avoid issues like "/api" + "users" = "/apiusers"
|
|
307
|
+
const routePath = joinRoutePaths(versionPrefix, controllerMetadata.path, metadata.path);
|
|
308
|
+
const fullPath = joinRoutePaths(this._routingConfig.rootPath, routePath);
|
|
309
|
+
// Register route for suggestions system (synchronous approach)
|
|
310
|
+
try {
|
|
311
|
+
const module = getRouteRegistryModule();
|
|
312
|
+
if (module && module.getRouteRegistry) {
|
|
313
|
+
const registry = module.getRouteRegistry();
|
|
314
|
+
registry.register(metadata.method, routePath, fullPath);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
// Route registry not available, skip registration (non-critical)
|
|
319
|
+
// This allows the app to work even if suggestions module isn't available
|
|
320
|
+
}
|
|
321
|
+
this._router[metadata.method](routePath, ...controllerMiddleware, ...routeMiddleware, handler);
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
this._app.use(this._routingConfig.rootPath, this._router);
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Initialize the interceptor system by binding required components
|
|
329
|
+
* @private
|
|
330
|
+
*/
|
|
331
|
+
initializeInterceptorSystem() {
|
|
332
|
+
try {
|
|
333
|
+
// Bind InterceptorRegistry if not already bound
|
|
334
|
+
if (!this._container.isBound(InterceptorRegistry)) {
|
|
335
|
+
this._container.bind(InterceptorRegistry).toSelf().inSingletonScope();
|
|
336
|
+
}
|
|
337
|
+
// Bind InterceptorExecutor if not already bound
|
|
338
|
+
if (!this._container.isBound(InterceptorExecutor)) {
|
|
339
|
+
this._container.bind(InterceptorExecutor).toSelf().inSingletonScope();
|
|
340
|
+
}
|
|
341
|
+
// Bind InterceptorMiddleware if not already bound
|
|
342
|
+
if (!this._container.isBound(InterceptorMiddleware)) {
|
|
343
|
+
this._container.bind(InterceptorMiddleware).toSelf().inSingletonScope();
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
catch {
|
|
347
|
+
// Interceptor system initialization failed (non-critical)
|
|
348
|
+
// Routes will work without interceptors
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Check if the interceptor system is properly initialized
|
|
353
|
+
* @private
|
|
354
|
+
*/
|
|
355
|
+
isInterceptorSystemReady() {
|
|
356
|
+
try {
|
|
357
|
+
return (this._container.isBound(InterceptorExecutor) &&
|
|
358
|
+
this._container.isBound(InterceptorMiddleware));
|
|
359
|
+
}
|
|
360
|
+
catch {
|
|
361
|
+
return false;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Extract interceptors from controller and method metadata
|
|
366
|
+
* @private
|
|
367
|
+
*/
|
|
368
|
+
extractInterceptors(controllerClass, methodName) {
|
|
369
|
+
try {
|
|
370
|
+
// Get controller-level interceptors
|
|
371
|
+
const controllerInterceptors = Reflect.getMetadata(INTERCEPTOR_METADATA_KEY.controllerInterceptors, controllerClass) || [];
|
|
372
|
+
// Get method-level interceptors
|
|
373
|
+
const methodInterceptors = Reflect.getMetadata(INTERCEPTOR_METADATA_KEY.methodInterceptors, controllerClass, methodName) || [];
|
|
374
|
+
// Combine: controller + method level
|
|
375
|
+
return [...controllerInterceptors, ...methodInterceptors];
|
|
376
|
+
}
|
|
377
|
+
catch {
|
|
378
|
+
return [];
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Wrap a handler with interceptor middleware
|
|
383
|
+
* @private
|
|
384
|
+
*/
|
|
385
|
+
wrapWithInterceptors(handler, controllerClass, methodName) {
|
|
386
|
+
try {
|
|
387
|
+
const interceptorMiddleware = createInterceptorMiddleware(this._container, controllerClass, methodName, handler);
|
|
388
|
+
return interceptorMiddleware;
|
|
389
|
+
}
|
|
390
|
+
catch {
|
|
391
|
+
// Fall back to original handler if interceptor wrapping fails
|
|
392
|
+
return handler;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Checks if a middleware item is a class constructor (not an instance).
|
|
397
|
+
* Handles classes that extend ExpressoMiddleware (which has abstract use method).
|
|
398
|
+
* Note: Abstract methods don't exist at runtime, so we check for concrete implementations.
|
|
399
|
+
*/
|
|
400
|
+
isMiddlewareClass(middlewareItem) {
|
|
401
|
+
// Must be a function (class constructor)
|
|
402
|
+
if (typeof middlewareItem !== "function") {
|
|
403
|
+
return false;
|
|
404
|
+
}
|
|
405
|
+
// Must not be a conditional or composed middleware config
|
|
406
|
+
if (isConditionalMiddleware(middlewareItem) || isComposedMiddleware(middlewareItem)) {
|
|
407
|
+
return false;
|
|
408
|
+
}
|
|
409
|
+
// Must have a prototype
|
|
410
|
+
if (middlewareItem.prototype === undefined) {
|
|
411
|
+
return false;
|
|
412
|
+
}
|
|
413
|
+
// Check if it has a 'use' method in its prototype
|
|
414
|
+
// Classes that extend ExpressoMiddleware must implement the abstract use() method
|
|
415
|
+
// so it will be in the prototype at runtime
|
|
416
|
+
const prototype = middlewareItem.prototype;
|
|
417
|
+
// Check for 'use' method directly in prototype (most common case)
|
|
418
|
+
if ("use" in prototype && typeof prototype.use === "function") {
|
|
419
|
+
return true;
|
|
420
|
+
}
|
|
421
|
+
// Also check prototype chain in case use() is defined in a parent class
|
|
422
|
+
// This handles cases where the method might be inherited (optimized: only if not found directly)
|
|
423
|
+
let currentPrototype = Object.getPrototypeOf(prototype);
|
|
424
|
+
while (currentPrototype && currentPrototype !== Object.prototype) {
|
|
425
|
+
if ("use" in currentPrototype &&
|
|
426
|
+
typeof currentPrototype.use === "function") {
|
|
427
|
+
return true;
|
|
428
|
+
}
|
|
429
|
+
currentPrototype = Object.getPrototypeOf(currentPrototype);
|
|
430
|
+
}
|
|
431
|
+
return false;
|
|
432
|
+
}
|
|
433
|
+
isExpressoMiddleware(middlewareItem) {
|
|
434
|
+
return (typeof middlewareItem === "object" &&
|
|
435
|
+
middlewareItem !== null &&
|
|
436
|
+
"use" in middlewareItem &&
|
|
437
|
+
typeof middlewareItem.use === "function" &&
|
|
438
|
+
!isConditionalMiddleware(middlewareItem) &&
|
|
439
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
440
|
+
!this.isMiddlewareClass(middlewareItem));
|
|
441
|
+
}
|
|
442
|
+
resolveMiddleware(...middleware) {
|
|
443
|
+
return middleware.map((middlewareItem) => {
|
|
444
|
+
// Handle composed middleware first (Phase 3: Middleware Composition)
|
|
445
|
+
if (isComposedMiddleware(middlewareItem)) {
|
|
446
|
+
return this.createComposedMiddlewareHandler(middlewareItem);
|
|
447
|
+
}
|
|
448
|
+
// Handle conditional middleware
|
|
449
|
+
if (isConditionalMiddleware(middlewareItem)) {
|
|
450
|
+
return this.createConditionalMiddlewareHandler(middlewareItem);
|
|
451
|
+
}
|
|
452
|
+
// Handle class constructors (Phase 2: Class Reference Support)
|
|
453
|
+
if (this.isMiddlewareClass(middlewareItem)) {
|
|
454
|
+
return this.createLazyMiddlewareHandler(middlewareItem);
|
|
455
|
+
}
|
|
456
|
+
if (this.isExpressoMiddleware(middlewareItem)) {
|
|
457
|
+
return (req, res, next) => {
|
|
458
|
+
middlewareItem.use(req, res, next);
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
if (!this._container.isBound(middlewareItem)) {
|
|
462
|
+
return middlewareItem;
|
|
463
|
+
}
|
|
464
|
+
const middlewareInstance = this._container.get(middlewareItem);
|
|
465
|
+
if (middlewareInstance instanceof BaseMiddleware) {
|
|
466
|
+
return (req, res, next) => {
|
|
467
|
+
const mReq = this._container.get(middlewareItem);
|
|
468
|
+
mReq.httpContext = this._getHttpContext(req);
|
|
469
|
+
mReq.handler(req, res, next);
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
return middlewareInstance;
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Creates a lazy middleware handler for class constructors.
|
|
477
|
+
* Supports both container-bound middleware (via @provide()) and direct instantiation.
|
|
478
|
+
*
|
|
479
|
+
* Performance: Instances are created per-request to support request-scoped state.
|
|
480
|
+
* For better performance with stateless middleware, use container-bound middleware
|
|
481
|
+
* with proper scoping (singleton/request scope) via @provide().
|
|
482
|
+
*
|
|
483
|
+
* Note: If container resolution fails (e.g., base class missing @injectable()),
|
|
484
|
+
* falls back to direct instantiation for backward compatibility.
|
|
485
|
+
*/
|
|
486
|
+
createLazyMiddlewareHandler(MiddlewareClass) {
|
|
487
|
+
// Pre-check if container-bound at route registration time (performance optimization)
|
|
488
|
+
const isContainerBound = this._container.isBound(MiddlewareClass);
|
|
489
|
+
let containerResolutionFailed = false;
|
|
490
|
+
// Cache instance for non-container-bound middleware (singleton per handler)
|
|
491
|
+
// Container-bound middleware relies on container scoping (singleton/request scope)
|
|
492
|
+
let cachedInstance;
|
|
493
|
+
return (req, res, next) => {
|
|
494
|
+
try {
|
|
495
|
+
let instance;
|
|
496
|
+
// Try container resolution first if bound and not previously failed
|
|
497
|
+
if (isContainerBound && !containerResolutionFailed) {
|
|
498
|
+
try {
|
|
499
|
+
// Resolve from container (supports DI, scoping, etc.)
|
|
500
|
+
// Container handles singleton/request scope automatically
|
|
501
|
+
instance = this._container.get(MiddlewareClass);
|
|
502
|
+
}
|
|
503
|
+
catch (containerError) {
|
|
504
|
+
// Container resolution failed (e.g., base class missing @injectable())
|
|
505
|
+
// Mark as failed and fall back to direct instantiation
|
|
506
|
+
containerResolutionFailed = true;
|
|
507
|
+
try {
|
|
508
|
+
// Create and cache instance if not already cached
|
|
509
|
+
if (!cachedInstance) {
|
|
510
|
+
cachedInstance = new MiddlewareClass();
|
|
511
|
+
}
|
|
512
|
+
instance = cachedInstance;
|
|
513
|
+
}
|
|
514
|
+
catch (instantiationError) {
|
|
515
|
+
next(instantiationError);
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
else {
|
|
521
|
+
// Create instance directly (no DI support or container not available)
|
|
522
|
+
// Cache instance for reuse across requests (singleton per handler)
|
|
523
|
+
if (!cachedInstance) {
|
|
524
|
+
try {
|
|
525
|
+
cachedInstance = new MiddlewareClass();
|
|
526
|
+
}
|
|
527
|
+
catch (instantiationError) {
|
|
528
|
+
next(instantiationError);
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
instance = cachedInstance;
|
|
533
|
+
}
|
|
534
|
+
// Execute middleware (supports both sync and async)
|
|
535
|
+
// The middleware's use() method should call next() itself
|
|
536
|
+
// We pass the next function directly - when middleware calls next(),
|
|
537
|
+
// it will continue the Express middleware chain (or the composition chain)
|
|
538
|
+
try {
|
|
539
|
+
const result = instance.use(req, res, next);
|
|
540
|
+
// Handle async middleware that returns a Promise
|
|
541
|
+
// If it returns a Promise, return it so the chain can await it
|
|
542
|
+
if (result !== undefined && result !== null) {
|
|
543
|
+
const resultObj = result;
|
|
544
|
+
if (typeof resultObj === "object" &&
|
|
545
|
+
resultObj !== null &&
|
|
546
|
+
"then" in resultObj &&
|
|
547
|
+
typeof resultObj.then === "function") {
|
|
548
|
+
// Return the Promise so the chain can await it
|
|
549
|
+
// The middleware should have already called next(), but the chain
|
|
550
|
+
// will wait for the Promise to resolve/reject
|
|
551
|
+
return result.catch((error) => {
|
|
552
|
+
// If the Promise rejects and next() wasn't called with error, call it now
|
|
553
|
+
next(error);
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
// Synchronous middleware - returns void, chain relies on next() being called
|
|
558
|
+
}
|
|
559
|
+
catch (useError) {
|
|
560
|
+
// If use() throws synchronously, pass error to next()
|
|
561
|
+
next(useError);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
catch (error) {
|
|
565
|
+
// Catch any other errors
|
|
566
|
+
next(error);
|
|
567
|
+
}
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* Creates a request handler for conditional middleware.
|
|
572
|
+
* Evaluates the condition and executes the wrapped middleware if condition is true.
|
|
573
|
+
*/
|
|
574
|
+
createConditionalMiddlewareHandler(config) {
|
|
575
|
+
// Resolve the wrapped middleware once (at route registration time)
|
|
576
|
+
const wrappedMiddlewareHandlers = this.resolveMiddleware(config.middleware);
|
|
577
|
+
return async (req, res, next) => {
|
|
578
|
+
try {
|
|
579
|
+
// Evaluate the condition (supports both sync and async)
|
|
580
|
+
const conditionResult = await config.condition(req);
|
|
581
|
+
// Determine if middleware should execute based on condition and skipOnFalse flag
|
|
582
|
+
const shouldExecute = config.skipOnFalse !== false ? conditionResult : !conditionResult;
|
|
583
|
+
if (shouldExecute) {
|
|
584
|
+
// Condition met, execute the wrapped middleware
|
|
585
|
+
// The wrapped middleware handlers are already Express RequestHandlers,
|
|
586
|
+
// so we can execute them directly. They will call next() when done,
|
|
587
|
+
// which will continue to the next middleware in the route.
|
|
588
|
+
if (wrappedMiddlewareHandlers.length === 0) {
|
|
589
|
+
// No middleware to execute, just continue
|
|
590
|
+
next();
|
|
591
|
+
}
|
|
592
|
+
else if (wrappedMiddlewareHandlers.length === 1) {
|
|
593
|
+
// Single middleware, execute it directly
|
|
594
|
+
wrappedMiddlewareHandlers[0](req, res, next);
|
|
595
|
+
}
|
|
596
|
+
else {
|
|
597
|
+
// Multiple middleware, execute them sequentially
|
|
598
|
+
await this.executeMiddlewareChain(wrappedMiddlewareHandlers, req, res, next);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
else {
|
|
602
|
+
// Condition not met, skip middleware and continue to next middleware in route
|
|
603
|
+
next();
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
catch (error) {
|
|
607
|
+
// If condition evaluation throws, pass error to error handler
|
|
608
|
+
next(error);
|
|
609
|
+
}
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Creates a request handler for composed middleware (Phase 3: Middleware Composition).
|
|
614
|
+
* Executes all middleware in the composition sequentially.
|
|
615
|
+
* Both 'combine' and 'sequence' types behave the same way - they execute middleware
|
|
616
|
+
* sequentially and propagate errors normally (Express handles errors via next(error)).
|
|
617
|
+
*
|
|
618
|
+
* @param config - ComposedMiddlewareConfig containing the middleware array and type
|
|
619
|
+
* @returns Express RequestHandler
|
|
620
|
+
*/
|
|
621
|
+
createComposedMiddlewareHandler(config) {
|
|
622
|
+
// Resolve all middleware in the composition to Express RequestHandlers
|
|
623
|
+
const resolvedHandlers = config.middleware.flatMap((mw) => this.resolveMiddleware(mw));
|
|
624
|
+
return async (req, res, next) => {
|
|
625
|
+
try {
|
|
626
|
+
if (resolvedHandlers.length === 0) {
|
|
627
|
+
// No middleware to execute, just continue
|
|
628
|
+
next();
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
// Execute all middleware sequentially
|
|
632
|
+
// Both 'combine' and 'sequence' use the same execution logic
|
|
633
|
+
// Express's error handling (via next(error)) naturally stops execution
|
|
634
|
+
await this.executeMiddlewareChain(resolvedHandlers, req, res, next);
|
|
635
|
+
}
|
|
636
|
+
catch (error) {
|
|
637
|
+
// If execution throws an error, pass it to Express error handler
|
|
638
|
+
next(error);
|
|
639
|
+
}
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* Executes a chain of middleware handlers sequentially.
|
|
644
|
+
* Each middleware calls next() to proceed to the next one.
|
|
645
|
+
* Handles both synchronous and asynchronous middleware.
|
|
646
|
+
*/
|
|
647
|
+
executeMiddlewareChain(handlers, req, res, next) {
|
|
648
|
+
return new Promise((resolve, reject) => {
|
|
649
|
+
let index = 0;
|
|
650
|
+
const runNext = (err) => {
|
|
651
|
+
if (err) {
|
|
652
|
+
reject(err);
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
if (index >= handlers.length) {
|
|
656
|
+
// All middleware executed successfully, call Express next() to continue to route handler
|
|
657
|
+
next();
|
|
658
|
+
resolve();
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
const handler = handlers[index++];
|
|
662
|
+
try {
|
|
663
|
+
// Execute the handler
|
|
664
|
+
// Express middleware handlers can:
|
|
665
|
+
// 1. Call next() synchronously
|
|
666
|
+
// 2. Call next() asynchronously
|
|
667
|
+
// 3. Return a Promise
|
|
668
|
+
// 4. Return nothing (void)
|
|
669
|
+
const result = handler(req, res, (err) => {
|
|
670
|
+
if (err) {
|
|
671
|
+
reject(err);
|
|
672
|
+
}
|
|
673
|
+
else {
|
|
674
|
+
// Handler called next() successfully, proceed to next middleware
|
|
675
|
+
runNext();
|
|
676
|
+
}
|
|
677
|
+
});
|
|
678
|
+
// If handler returns a Promise, wait for it
|
|
679
|
+
// Note: Even if handler returns a Promise, it should still call next()
|
|
680
|
+
// But we handle the Promise in case it doesn't
|
|
681
|
+
// Check if result exists and is a Promise-like object (thenable)
|
|
682
|
+
if (result !== undefined && result !== null) {
|
|
683
|
+
const resultObj = result;
|
|
684
|
+
if (typeof resultObj === "object" &&
|
|
685
|
+
resultObj !== null &&
|
|
686
|
+
"then" in resultObj &&
|
|
687
|
+
typeof resultObj.then === "function") {
|
|
688
|
+
result
|
|
689
|
+
.then(() => {
|
|
690
|
+
// If Promise resolves and next wasn't called, proceed
|
|
691
|
+
if (index <= handlers.length) {
|
|
692
|
+
runNext();
|
|
693
|
+
}
|
|
694
|
+
})
|
|
695
|
+
.catch(reject);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
// If handler doesn't return a Promise and doesn't call next(),
|
|
699
|
+
// we rely on the handler to call next() itself
|
|
700
|
+
}
|
|
701
|
+
catch (error) {
|
|
702
|
+
reject(error);
|
|
703
|
+
}
|
|
704
|
+
};
|
|
705
|
+
runNext();
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
copyHeadersTo(headers, target) {
|
|
709
|
+
for (const name of Object.keys(headers)) {
|
|
710
|
+
const headerValue = headers[name];
|
|
711
|
+
target.append(name, typeof headerValue === "number" ? headerValue.toString() : headerValue);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
async handleHttpResponseMessage(message, res) {
|
|
715
|
+
this.copyHeadersTo(message.headers, res);
|
|
716
|
+
if (message.content !== undefined) {
|
|
717
|
+
this.copyHeadersTo(message.content.headers, res);
|
|
718
|
+
res
|
|
719
|
+
.status(message.statusCode)
|
|
720
|
+
// If the content is a number, ensure we change it to a string, else our content is
|
|
721
|
+
// treated as a statusCode rather than as the content of the Response
|
|
722
|
+
.send(await message.content.readAsync());
|
|
723
|
+
}
|
|
724
|
+
else {
|
|
725
|
+
res.sendStatus(message.statusCode);
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
handlerFactory(controllerName, key, parameterMetadata, controllerConstructor, methodMetadata) {
|
|
729
|
+
// Extract guards from controller and method metadata
|
|
730
|
+
const controllerGuards = controllerConstructor
|
|
731
|
+
? getControllerGuards(controllerConstructor)
|
|
732
|
+
: [];
|
|
733
|
+
const methodGuards = controllerConstructor ? getMethodGuards(controllerConstructor, key) : [];
|
|
734
|
+
const allGuards = [...controllerGuards, ...methodGuards];
|
|
735
|
+
// Create guard middleware if guards exist
|
|
736
|
+
let guardMiddleware = null;
|
|
737
|
+
if (allGuards.length > 0) {
|
|
738
|
+
try {
|
|
739
|
+
// Check if guard system is initialized (use class identifiers, not strings)
|
|
740
|
+
if (this._container.isBound(GuardExecutor) &&
|
|
741
|
+
this._container.isBound(GuardContextFactory) &&
|
|
742
|
+
this._container.isBound(GuardMiddleware)) {
|
|
743
|
+
const guardMiddlewareInstance = this._container.get(GuardMiddleware);
|
|
744
|
+
guardMiddleware = guardMiddlewareInstance.execute;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
catch (error) {
|
|
748
|
+
// Guard system not initialized, continue without guards
|
|
749
|
+
console.error("[Guard System] Failed to initialize:", error);
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
// Create handler function
|
|
753
|
+
const handler = async (req, res, next) => {
|
|
754
|
+
try {
|
|
755
|
+
// Attach controller and method metadata to request for exception handler middleware
|
|
756
|
+
// This provides a reliable fallback if route stack extraction fails
|
|
757
|
+
if (controllerConstructor) {
|
|
758
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
759
|
+
req.__expressotsController = controllerConstructor;
|
|
760
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
761
|
+
req.__expressotsMethod = key;
|
|
762
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
763
|
+
req.__expressotsControllerName = controllerName;
|
|
764
|
+
// Attach guards to request for guard middleware
|
|
765
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
766
|
+
req.__expressotsControllerGuards = controllerGuards;
|
|
767
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
768
|
+
req.__expressotsMethodGuards = methodGuards;
|
|
769
|
+
}
|
|
770
|
+
// Execute guard middleware if guards exist
|
|
771
|
+
if (guardMiddleware && allGuards.length > 0) {
|
|
772
|
+
return guardMiddleware(req, res, async (err) => {
|
|
773
|
+
if (err) {
|
|
774
|
+
return next(err);
|
|
775
|
+
}
|
|
776
|
+
// Guards passed, continue to route handler
|
|
777
|
+
await this.executeRouteHandler(req, res, next, controllerName, key, parameterMetadata, controllerConstructor);
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
// No guards, execute route handler directly
|
|
781
|
+
await this.executeRouteHandler(req, res, next, controllerName, key, parameterMetadata, controllerConstructor);
|
|
782
|
+
}
|
|
783
|
+
catch (error) {
|
|
784
|
+
next(error);
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
return handler;
|
|
788
|
+
}
|
|
789
|
+
async executeRouteHandler(req, res, next, controllerName, key, parameterMetadata, controllerConstructor) {
|
|
790
|
+
// Get request ID for flow tracking
|
|
791
|
+
const requestContext = ContextManager.getCurrentContext();
|
|
792
|
+
const requestId = requestContext?.requestId;
|
|
793
|
+
const flowTracker = requestId ? findFlowTracker(requestId) : undefined;
|
|
794
|
+
const controllerStepName = `${controllerName}.${key}`;
|
|
795
|
+
try {
|
|
796
|
+
let args = this.extractParameters(req, res, next, parameterMetadata);
|
|
797
|
+
const httpContext = this._getHttpContext(req);
|
|
798
|
+
httpContext.container.bind(TYPE.HttpContext).toConstantValue(httpContext);
|
|
799
|
+
// Validate parameters if validation service is enabled
|
|
800
|
+
const validationService = this.getValidationService();
|
|
801
|
+
if (validationService?.isEnabled() && controllerConstructor) {
|
|
802
|
+
// Check if there are actually validation metadata (has @validatedBody, @validatedQuery, etc.)
|
|
803
|
+
const validationMetadata = getValidationMetadata(controllerConstructor, key);
|
|
804
|
+
const hasValidatedParams = validationMetadata.length > 0;
|
|
805
|
+
if (hasValidatedParams) {
|
|
806
|
+
// Start validation step only if there are validated parameters
|
|
807
|
+
if (flowTracker?.isEnabled()) {
|
|
808
|
+
flowTracker.startStep("validation", `Validation: ${controllerName}.${key}`);
|
|
809
|
+
}
|
|
810
|
+
const validatedArgs = await validationService.validateParameters(req, res, controllerConstructor, key, args);
|
|
811
|
+
if (validatedArgs === null) {
|
|
812
|
+
// Validation failed, response already sent
|
|
813
|
+
// Create a validation error to store on request
|
|
814
|
+
const validationError = new Error("Validation failed");
|
|
815
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
816
|
+
req.__expressotsFlowError = validationError;
|
|
817
|
+
if (flowTracker?.isEnabled()) {
|
|
818
|
+
flowTracker.failStep(validationError);
|
|
819
|
+
}
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
// End validation step
|
|
823
|
+
if (flowTracker?.isEnabled()) {
|
|
824
|
+
flowTracker.endStep("success");
|
|
825
|
+
}
|
|
826
|
+
args = validatedArgs;
|
|
827
|
+
}
|
|
828
|
+
else {
|
|
829
|
+
// No validation metadata, but validation service might still run smart detection
|
|
830
|
+
// Only track if smart detection actually finds something to validate
|
|
831
|
+
const validatedArgs = await validationService.validateParameters(req, res, controllerConstructor, key, args);
|
|
832
|
+
if (validatedArgs === null) {
|
|
833
|
+
// Smart detection found validation errors
|
|
834
|
+
return;
|
|
835
|
+
}
|
|
836
|
+
args = validatedArgs;
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
// Start controller step
|
|
840
|
+
if (flowTracker?.isEnabled()) {
|
|
841
|
+
flowTracker.startStep("controller", controllerStepName, {
|
|
842
|
+
controller: controllerName,
|
|
843
|
+
method: key,
|
|
844
|
+
});
|
|
845
|
+
}
|
|
846
|
+
// invoke controller's action
|
|
847
|
+
const controller = httpContext.container.getNamed(TYPE.Controller, controllerName);
|
|
848
|
+
const value = await controller[key](...args);
|
|
849
|
+
// End controller step
|
|
850
|
+
if (flowTracker?.isEnabled()) {
|
|
851
|
+
flowTracker.endStep("success");
|
|
852
|
+
}
|
|
853
|
+
const { template, defaultData } = getRenderMetadata(controller, key);
|
|
854
|
+
if (template) {
|
|
855
|
+
const data = value || defaultData || {};
|
|
856
|
+
res.render(template, data);
|
|
857
|
+
}
|
|
858
|
+
else if (value instanceof HttpResponseMessage) {
|
|
859
|
+
await this.handleHttpResponseMessage(value, res);
|
|
860
|
+
}
|
|
861
|
+
else if (instanceOfIHttpActionResult(value)) {
|
|
862
|
+
const httpResponseMessage = await value.executeAsync();
|
|
863
|
+
await this.handleHttpResponseMessage(httpResponseMessage, res);
|
|
864
|
+
}
|
|
865
|
+
else if (value instanceof Function) {
|
|
866
|
+
value();
|
|
867
|
+
}
|
|
868
|
+
else if (!res.headersSent) {
|
|
869
|
+
// Smart response handling: Auto-404 for GET requests returning null/undefined
|
|
870
|
+
// This is a common pattern where null means "resource not found"
|
|
871
|
+
if (value === null || value === undefined) {
|
|
872
|
+
const method = req.method.toUpperCase();
|
|
873
|
+
// For GET requests, null/undefined typically means "not found"
|
|
874
|
+
// For DELETE requests, undefined means "successfully deleted" (204 No Content is already set)
|
|
875
|
+
if (method === "GET") {
|
|
876
|
+
// Extract resource info from path for helpful error message
|
|
877
|
+
const pathParts = req.path.split("/").filter(Boolean);
|
|
878
|
+
const resource = pathParts[pathParts.length - 2] || "Resource";
|
|
879
|
+
const id = req.params?.id || pathParts[pathParts.length - 1];
|
|
880
|
+
throw new NotFoundError(resource, id);
|
|
881
|
+
}
|
|
882
|
+
// For other methods (DELETE, PUT, PATCH), undefined is valid (204 No Content)
|
|
883
|
+
// The HttpStatusCodeMiddleware already sets appropriate status codes
|
|
884
|
+
if (method !== "DELETE" && method !== "PUT" && method !== "PATCH") {
|
|
885
|
+
// For POST or other methods with null/undefined, send empty response
|
|
886
|
+
res.end();
|
|
887
|
+
}
|
|
888
|
+
// For DELETE/PUT/PATCH, the middleware already set 204, just end the response
|
|
889
|
+
else {
|
|
890
|
+
res.end();
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
else {
|
|
894
|
+
// Try content negotiation if enabled
|
|
895
|
+
const cnMetadata = getContentNegotiationMetadata(controller, key);
|
|
896
|
+
const contentNegotiationService = this.getContentNegotiationService();
|
|
897
|
+
if (contentNegotiationService?.isEnabled()) {
|
|
898
|
+
const handled = await contentNegotiationService.handleResponse(req, res, value, cnMetadata.accept || cnMetadata.produces);
|
|
899
|
+
if (handled) {
|
|
900
|
+
return; // Response already sent
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
// Fallback to default behavior (backward compatible)
|
|
904
|
+
res.send(value);
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
catch (err) {
|
|
909
|
+
// Store error on request for flow tracking
|
|
910
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
911
|
+
req.__expressotsFlowError = err instanceof Error ? err : new Error(String(err));
|
|
912
|
+
// End controller step with failure if not already ended
|
|
913
|
+
if (flowTracker?.isEnabled()) {
|
|
914
|
+
const currentFlow = flowTracker.getFlow();
|
|
915
|
+
const lastStep = currentFlow.steps[currentFlow.steps.length - 1];
|
|
916
|
+
if (lastStep && lastStep.name === controllerStepName && lastStep.status === "success") {
|
|
917
|
+
// Step was already ended, don't end again
|
|
918
|
+
}
|
|
919
|
+
else {
|
|
920
|
+
flowTracker.failStep(err instanceof Error ? err : undefined);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
next(err);
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
_getHttpContext(req) {
|
|
927
|
+
return getHttpContext(req);
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Sets the content negotiation service instance.
|
|
931
|
+
* @param service - Content negotiation service instance
|
|
932
|
+
*/
|
|
933
|
+
setContentNegotiationService(service) {
|
|
934
|
+
this._contentNegotiationService = service;
|
|
935
|
+
}
|
|
936
|
+
/**
|
|
937
|
+
* Gets the content negotiation service if available.
|
|
938
|
+
* @returns Content negotiation service or undefined
|
|
939
|
+
*/
|
|
940
|
+
getContentNegotiationService() {
|
|
941
|
+
return this._contentNegotiationService;
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* Sets the validation service instance.
|
|
945
|
+
* @param service - Validation service instance
|
|
946
|
+
*/
|
|
947
|
+
setValidationService(service) {
|
|
948
|
+
this._validationService = service;
|
|
949
|
+
}
|
|
950
|
+
/**
|
|
951
|
+
* Gets the validation service if available.
|
|
952
|
+
* @returns Validation service or undefined
|
|
953
|
+
*/
|
|
954
|
+
getValidationService() {
|
|
955
|
+
return this._validationService;
|
|
956
|
+
}
|
|
957
|
+
async _createHttpContext(req, res, next) {
|
|
958
|
+
const principal = await this._getCurrentUser(req, res, next);
|
|
959
|
+
return {
|
|
960
|
+
// We use a childContainer for each request so we can be
|
|
961
|
+
// sure that the binding is unique for each HTTP request
|
|
962
|
+
container: this._container.createChild(),
|
|
963
|
+
request: req,
|
|
964
|
+
response: res,
|
|
965
|
+
user: principal,
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
async _getCurrentUser(req, res, next) {
|
|
969
|
+
// Check if AuthProvider is available (either via constructor or bound via setupAuthorizationForExpress)
|
|
970
|
+
if (this._AuthProvider !== undefined || this._container.isBound(TYPE.AuthProvider)) {
|
|
971
|
+
const authProvider = this._container.get(TYPE.AuthProvider);
|
|
972
|
+
return authProvider.getUser(req, res, next);
|
|
973
|
+
}
|
|
974
|
+
return Promise.resolve({
|
|
975
|
+
details: null,
|
|
976
|
+
isAuthenticated: () => Promise.resolve(false),
|
|
977
|
+
isInRole: (_role) => Promise.resolve(false),
|
|
978
|
+
isResourceOwner: (_resourceId) => Promise.resolve(false),
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
extractParameters(req, res, next, params) {
|
|
982
|
+
const args = [];
|
|
983
|
+
if (!params || !params.length) {
|
|
984
|
+
return [req, res, next];
|
|
985
|
+
}
|
|
986
|
+
params.forEach(({ type, index, parameterName, injectRoot }) => {
|
|
987
|
+
switch (type) {
|
|
988
|
+
case PARAMETER_TYPE.REQUEST:
|
|
989
|
+
args[index] = req;
|
|
990
|
+
break;
|
|
991
|
+
case PARAMETER_TYPE.NEXT:
|
|
992
|
+
args[index] = next;
|
|
993
|
+
break;
|
|
994
|
+
case PARAMETER_TYPE.PARAMS:
|
|
995
|
+
args[index] = this.getParam(req, "params", injectRoot, parameterName);
|
|
996
|
+
break;
|
|
997
|
+
case PARAMETER_TYPE.QUERY:
|
|
998
|
+
args[index] = this.getParam(req, "query", injectRoot, parameterName);
|
|
999
|
+
break;
|
|
1000
|
+
case PARAMETER_TYPE.BODY:
|
|
1001
|
+
args[index] = req.body;
|
|
1002
|
+
break;
|
|
1003
|
+
case PARAMETER_TYPE.HEADERS:
|
|
1004
|
+
args[index] = this.getParam(req, "headers", injectRoot, parameterName);
|
|
1005
|
+
break;
|
|
1006
|
+
case PARAMETER_TYPE.COOKIES:
|
|
1007
|
+
args[index] = this.getParam(req, "cookies", injectRoot, parameterName);
|
|
1008
|
+
break;
|
|
1009
|
+
case PARAMETER_TYPE.PRINCIPAL:
|
|
1010
|
+
args[index] = this._getPrincipal(req);
|
|
1011
|
+
break;
|
|
1012
|
+
default:
|
|
1013
|
+
args[index] = res;
|
|
1014
|
+
break; // response
|
|
1015
|
+
}
|
|
1016
|
+
});
|
|
1017
|
+
args.push(req, res, next);
|
|
1018
|
+
return args;
|
|
1019
|
+
}
|
|
1020
|
+
getParam(source, paramType, injectRoot, name) {
|
|
1021
|
+
const key = paramType === "headers" ? name?.toLowerCase() : name;
|
|
1022
|
+
const param = source[paramType];
|
|
1023
|
+
if (injectRoot) {
|
|
1024
|
+
return param;
|
|
1025
|
+
}
|
|
1026
|
+
return param && key ? param[key] : undefined;
|
|
1027
|
+
}
|
|
1028
|
+
_getPrincipal(req) {
|
|
1029
|
+
return this._getHttpContext(req).user;
|
|
1030
|
+
}
|
|
1031
|
+
}
|