jimpex 9.0.0 → 10.0.0
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/CHANGELOG.md +20 -0
- package/dist/app/index.d.mts +1 -1
- package/dist/app/index.d.ts +1 -1
- package/dist/app/jimpex.d.mts +1 -1
- package/dist/app/jimpex.d.ts +1 -1
- package/dist/app/jimpex.js +13 -2
- package/dist/app/jimpex.js.map +1 -1
- package/dist/controllers/common/config.d.mts +2 -2
- package/dist/controllers/common/config.d.ts +2 -2
- package/dist/controllers/common/health.d.mts +3 -3
- package/dist/controllers/common/health.d.ts +3 -3
- package/dist/controllers/common/index.d.mts +2 -1
- package/dist/controllers/common/index.d.ts +2 -1
- package/dist/controllers/common/statics.d.mts +10 -2
- package/dist/controllers/common/statics.d.ts +10 -2
- package/dist/controllers/common/statics.js +9 -3
- package/dist/controllers/common/statics.js.map +1 -1
- package/dist/controllers/index.d.mts +2 -1
- package/dist/controllers/index.d.ts +2 -1
- package/dist/controllers/utils/gateway.d.mts +2 -2
- package/dist/controllers/utils/gateway.d.ts +2 -2
- package/dist/controllers/utils/gateway.js +3 -0
- package/dist/controllers/utils/gateway.js.map +1 -1
- package/dist/controllers/utils/index.d.mts +1 -1
- package/dist/controllers/utils/index.d.ts +1 -1
- package/dist/esm/app/jimpex.js +14 -3
- package/dist/esm/app/jimpex.js.map +1 -1
- package/dist/esm/{chunk-2B2CG5KL.js → chunk-F3FYYIAV.js} +1 -1
- package/dist/esm/controllers/common/config.js +1 -1
- package/dist/esm/controllers/common/health.js +1 -1
- package/dist/esm/controllers/common/statics.js +10 -4
- package/dist/esm/controllers/common/statics.js.map +1 -1
- package/dist/esm/controllers/utils/gateway.js +4 -1
- package/dist/esm/controllers/utils/gateway.js.map +1 -1
- package/dist/esm/middlewares/common/errorHandler.js +1 -1
- package/dist/esm/middlewares/common/forceHTTPS.js +1 -1
- package/dist/esm/middlewares/common/hsts.js +1 -1
- package/dist/esm/middlewares/html/fastHTML.js +1 -1
- package/dist/esm/middlewares/html/showHTML.js +1 -1
- package/dist/esm/middlewares/utils/versionValidator.js +1 -1
- package/dist/esm/services/common/appError.js +1 -1
- package/dist/esm/services/common/httpError.js +1 -1
- package/dist/esm/services/common/index.js +1 -1
- package/dist/esm/services/common/sendFile.js +1 -1
- package/dist/esm/services/frontend/frontendFs.js +1 -1
- package/dist/esm/services/frontend/index.js +1 -1
- package/dist/esm/services/html/htmlGenerator.js +1 -1
- package/dist/esm/services/html/index.js +1 -1
- package/dist/esm/services/http/apiClient.js +1 -1
- package/dist/esm/services/http/http.js +11 -5
- package/dist/esm/services/http/http.js.map +1 -1
- package/dist/esm/services/http/index.js +1 -1
- package/dist/esm/services/http/responsesBuilder.js +1 -1
- package/dist/esm/services/utils/ensureBearerToken.js +1 -1
- package/dist/esm/services/utils/index.js +1 -1
- package/dist/esm/utils/fns/others.js +1 -1
- package/dist/esm/utils/fns/routes.js +1 -1
- package/dist/esm/utils/fns/statuses.js +1 -1
- package/dist/esm/utils/fns/text.js +1 -1
- package/dist/esm/utils/wrappers.js +1 -1
- package/dist/{index-efeb437e.d.ts → index-Bwf7JHu9.d.mts} +6 -1
- package/dist/{index-b2a04c78.d.ts → index-C6I3NCC-.d.ts} +6 -1
- package/dist/index.d.mts +3 -2
- package/dist/index.d.ts +3 -2
- package/dist/middlewares/common/errorHandler.d.mts +3 -3
- package/dist/middlewares/common/errorHandler.d.ts +3 -3
- package/dist/middlewares/common/forceHTTPS.d.mts +3 -3
- package/dist/middlewares/common/forceHTTPS.d.ts +3 -3
- package/dist/middlewares/common/hsts.d.mts +3 -3
- package/dist/middlewares/common/hsts.d.ts +3 -3
- package/dist/middlewares/common/index.d.mts +1 -1
- package/dist/middlewares/common/index.d.ts +1 -1
- package/dist/middlewares/html/fastHTML.d.mts +2 -2
- package/dist/middlewares/html/fastHTML.d.ts +2 -2
- package/dist/middlewares/html/index.d.mts +1 -1
- package/dist/middlewares/html/index.d.ts +1 -1
- package/dist/middlewares/html/showHTML.d.mts +2 -2
- package/dist/middlewares/html/showHTML.d.ts +2 -2
- package/dist/middlewares/index.d.mts +1 -1
- package/dist/middlewares/index.d.ts +1 -1
- package/dist/middlewares/utils/index.d.mts +1 -1
- package/dist/middlewares/utils/index.d.ts +1 -1
- package/dist/middlewares/utils/versionValidator.d.mts +2 -2
- package/dist/middlewares/utils/versionValidator.d.ts +2 -2
- package/dist/services/common/appError.d.mts +2 -2
- package/dist/services/common/appError.d.ts +2 -2
- package/dist/services/common/httpError.d.mts +2 -2
- package/dist/services/common/httpError.d.ts +2 -2
- package/dist/services/common/index.d.mts +1 -1
- package/dist/services/common/index.d.ts +1 -1
- package/dist/services/common/sendFile.d.mts +2 -2
- package/dist/services/common/sendFile.d.ts +2 -2
- package/dist/services/frontend/frontendFs.d.mts +2 -2
- package/dist/services/frontend/frontendFs.d.ts +2 -2
- package/dist/services/frontend/index.d.mts +1 -1
- package/dist/services/frontend/index.d.ts +1 -1
- package/dist/services/html/htmlGenerator.d.mts +2 -2
- package/dist/services/html/htmlGenerator.d.ts +2 -2
- package/dist/services/html/index.d.mts +1 -1
- package/dist/services/html/index.d.ts +1 -1
- package/dist/services/http/apiClient.d.mts +2 -2
- package/dist/services/http/apiClient.d.ts +2 -2
- package/dist/services/http/http.d.mts +14 -8
- package/dist/services/http/http.d.ts +14 -8
- package/dist/services/http/http.js +10 -4
- package/dist/services/http/http.js.map +1 -1
- package/dist/services/http/index.d.mts +1 -1
- package/dist/services/http/index.d.ts +1 -1
- package/dist/services/http/responsesBuilder.d.mts +2 -2
- package/dist/services/http/responsesBuilder.d.ts +2 -2
- package/dist/services/index.d.mts +1 -1
- package/dist/services/index.d.ts +1 -1
- package/dist/services/utils/ensureBearerToken.d.mts +3 -3
- package/dist/services/utils/ensureBearerToken.d.ts +3 -3
- package/dist/services/utils/index.d.mts +1 -1
- package/dist/services/utils/index.d.ts +1 -1
- package/dist/types/events.d.mts +1 -1
- package/dist/types/events.d.ts +1 -1
- package/dist/types/express.d.mts +1 -1
- package/dist/types/express.d.ts +1 -1
- package/dist/types/http.d.mts +5 -2
- package/dist/types/http.d.ts +5 -2
- package/dist/types/http.js.map +1 -1
- package/dist/types/index.d.mts +2 -2
- package/dist/types/index.d.ts +2 -2
- package/dist/types/options.d.mts +1 -1
- package/dist/types/options.d.ts +1 -1
- package/dist/types/utils.d.mts +1 -1
- package/dist/types/utils.d.ts +1 -1
- package/dist/utils/fns/statuses.d.mts +1 -1
- package/dist/utils/fns/statuses.d.ts +1 -1
- package/dist/utils/index.d.mts +1 -1
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/wrappers.d.mts +1 -1
- package/dist/utils/wrappers.d.ts +1 -1
- package/package.json +45 -44
- package/src/app/jimpex.ts +15 -2
- package/src/controllers/common/statics.ts +13 -2
- package/src/controllers/utils/gateway.ts +4 -0
- package/src/services/http/http.ts +13 -4
- package/src/types/http.ts +3 -0
- /package/dist/esm/{chunk-2B2CG5KL.js.map → chunk-F3FYYIAV.js.map} +0 -0
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
__publicField
|
|
3
|
-
} from "../../chunk-
|
|
3
|
+
} from "../../chunk-F3FYYIAV.js";
|
|
4
4
|
import * as path from "path";
|
|
5
|
-
import * as mime from "mime";
|
|
6
5
|
import { deepAssignWithOverwrite } from "@homer0/deep-assign";
|
|
7
6
|
import {
|
|
8
7
|
controllerCreator,
|
|
@@ -18,6 +17,11 @@ class StaticsController {
|
|
|
18
17
|
* The service that serves static files.
|
|
19
18
|
*/
|
|
20
19
|
__publicField(this, "_sendFile");
|
|
20
|
+
/**
|
|
21
|
+
* The MIME type library. Since it's an ESM only module, Jimpex loads it on boot and makes
|
|
22
|
+
* it available on the container.
|
|
23
|
+
*/
|
|
24
|
+
__publicField(this, "_mime");
|
|
21
25
|
/**
|
|
22
26
|
* The controller customization options.
|
|
23
27
|
*/
|
|
@@ -28,6 +32,7 @@ class StaticsController {
|
|
|
28
32
|
*/
|
|
29
33
|
__publicField(this, "files");
|
|
30
34
|
this._sendFile = inject.sendFile;
|
|
35
|
+
this._mime = inject.mime;
|
|
31
36
|
this._options = this._validateOptions(
|
|
32
37
|
deepAssignWithOverwrite(
|
|
33
38
|
{
|
|
@@ -86,7 +91,7 @@ class StaticsController {
|
|
|
86
91
|
return (_, res, next) => {
|
|
87
92
|
const extension = path.parse(file.path).ext.substring(1);
|
|
88
93
|
const headers = {
|
|
89
|
-
"Content-Type":
|
|
94
|
+
"Content-Type": this._mime.getType(extension) || "text/html",
|
|
90
95
|
...file.headers
|
|
91
96
|
};
|
|
92
97
|
Object.entries(headers).forEach(([key, value]) => {
|
|
@@ -197,7 +202,8 @@ const staticsController = controllerCreator(
|
|
|
197
202
|
const router = app.getRouter();
|
|
198
203
|
const ctrl = new StaticsController({
|
|
199
204
|
inject: {
|
|
200
|
-
sendFile: app.get("sendFile")
|
|
205
|
+
sendFile: app.get("sendFile"),
|
|
206
|
+
mime: app.get("mime")
|
|
201
207
|
},
|
|
202
208
|
...options
|
|
203
209
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/controllers/common/statics.ts"],"sourcesContent":["import * as path from 'path';\nimport * as mime from 'mime';\nimport { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport {\n controllerCreator,\n removeSlashes,\n notUndefined,\n type MiddlewareLike,\n} from '../../utils';\nimport type { SendFile } from '../../services';\nimport type { Jimpex } from '../../app';\nimport type { DeepPartial, ExpressMiddleware, Router, RouterMethod } from '../../types';\n/**\n * The definition for each file the controller handles.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerFile = {\n /**\n * The route, relative to the controller root, to the file.\n */\n route: string;\n /**\n * The path to the file in the filesystem. Since the file is served using the\n * {@link SendFile} service, whether the file is relative to the project root or the\n * application executable depends on how the service is configured (relative to the\n * executable by default).\n */\n path: string;\n /**\n * A dictionary of headers for the response.\n */\n headers?: Record<string, string>;\n};\n/**\n * These are like \"master paths\" that get prepended to all the file paths and routes the\n * controller use.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerPathsOptions = {\n /**\n * A custom route to prefix all the file routes with.\n */\n route: string;\n /**\n * A custom path to prefix all the file paths with.\n */\n source: string;\n};\n/**\n * The options to customize the controller.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerOptions = {\n /**\n * A list of filenames, or definitions for the files to handle.\n */\n files: Array<string | StaticsControllerFile>;\n /**\n * A dictionary with the allowed router (HTTP) methods the controller can use to serve\n * the files. If `all` is set to `true`, the rest of the values will be ignored.\n *\n * @default {get: true, all: false}\n */\n methods: Partial<Record<RouterMethod, boolean>>;\n /**\n * The \"master paths\" the controller can use to prefix the file paths and routes.\n *\n * @default {route: '', source: './',}\n */\n paths: StaticsControllerPathsOptions;\n};\n/**\n * The options to construct a {@link StaticsController}.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerConstructorOptions =\n DeepPartial<StaticsControllerOptions> & {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n sendFile: SendFile;\n };\n };\n/**\n * A function to generate a list of middlewares that can be executed before the tontroller\n * main middleware.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerGetMiddlewaresFn = (app: Jimpex) => MiddlewareLike[];\n/**\n * The options for the controller creator that mounts {@link StaticsController}.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerCreatorOptions = DeepPartial<StaticsControllerOptions> & {\n /**\n * A function to generate a list of middlewares that can be executed before the\n * tontroller main middleware.\n */\n getMiddlewares?: StaticsControllerGetMiddlewaresFn;\n};\n/**\n * The options for {@link StaticsController._addRoute}.\n *\n * @access protected\n * @group Controllers/Statics\n */\nexport type AddStaticRouteOptions = {\n /**\n * The reference for the router in which the middlewares will be added.\n */\n router: Router;\n /**\n * The router method in which the middlewares will be added.\n */\n method: RouterMethod;\n /**\n * The definition of the file to serve.\n */\n file: StaticsControllerFile;\n /**\n * The middleware created by {@link StaticsController}, that will serve the file.\n */\n fileMiddleware: ExpressMiddleware;\n /**\n * A list of extra middlewares to execute before the file middleware.\n */\n middlewares: ExpressMiddleware[];\n};\n\n/**\n * The controller class that allows the application to serve specific files from any\n * folder to any route without the need of mounting directories as \"static\".\n *\n * @group Controller Classes\n * @group Controllers/Statics\n * @prettierignore\n */\nexport class StaticsController {\n /**\n * The service that serves static files.\n */\n protected readonly _sendFile: SendFile;\n /**\n * The controller customization options.\n */\n protected _options: StaticsControllerOptions;\n /**\n * A dictionary with the formatted definitions of the files that will be served.\n * It uses the files' routes as keys, for easy access in the middleware.\n */\n protected files: Record<string, StaticsControllerFile>;\n /**\n * @param options The options to construct the controller.\n */\n constructor({ inject, ...options }: StaticsControllerConstructorOptions) {\n this._sendFile = inject.sendFile;\n this._options = this._validateOptions(\n deepAssignWithOverwrite(\n {\n files: ['favicon.ico', 'index.html'],\n methods: options.methods || {\n all: false,\n get: true,\n },\n paths: {\n route: '',\n source: './',\n },\n },\n options,\n ),\n );\n this.files = this._createFiles();\n }\n /**\n * Mounts the middlewares in the router in order to serve the files.\n *\n * @param router A reference to the application router.\n * @param middlewares A list of extra middlewares to execute before the file\n * middleware.\n */\n addRoutes(router: Router, middlewares: ExpressMiddleware[] = []): Router {\n const { methods } = this._options;\n const use: RouterMethod[] = methods.all\n ? ['all']\n : Object.keys(methods).reduce<RouterMethod[]>((acc, name) => {\n const methodName = name as RouterMethod;\n if (methods[methodName]) {\n acc.push(methodName);\n }\n\n return acc;\n }, []);\n\n Object.keys(this.files).forEach((route) => {\n const file = this.files[route as keyof typeof this.files]!;\n const fileMiddleware = this._getMiddleware(file);\n use.forEach((method) =>\n this._addRoute({ router, method, file, fileMiddleware, middlewares }),\n );\n });\n\n return router;\n }\n /**\n * The controller options.\n */\n get options(): Readonly<StaticsControllerOptions> {\n return { ...this._options };\n }\n /**\n * Generates the middleware that will serve the file.\n *\n * @param file The definition of the file to serve.\n */\n protected _getMiddleware(file: StaticsControllerFile): ExpressMiddleware {\n return (_, res, next) => {\n const extension = path.parse(file.path).ext.substring(1);\n const headers = {\n 'Content-Type': mime.getType(extension) || 'text/html',\n ...file.headers,\n };\n\n Object.entries(headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n\n this._sendFile({\n res,\n filepath: file.path,\n next,\n });\n };\n }\n /**\n * Mounts the middleware(s) for a file in the router.\n *\n * @param options The information of the file and how it needs to be added.\n */\n protected _addRoute({\n router,\n method,\n file,\n fileMiddleware,\n middlewares,\n }: AddStaticRouteOptions): void {\n const { route } = file;\n router[method](route, [...middlewares, fileMiddleware]);\n }\n /**\n * Validates and formats the options sent to the constructor in order to get the final\n * set that will be stored in the controller.\n *\n * @param options The options to validate.\n * @throws If no files are specified.\n * @throws If methods is not defined.\n * @throws If no methods are enabled.\n * @throws If there's an invalid HTTP method.\n */\n protected _validateOptions(\n options: StaticsControllerOptions,\n ): StaticsControllerOptions {\n if (!options.files || !options.files.length) {\n throw new Error('You need to specify a list of files');\n }\n\n if (!options.methods) {\n throw new Error('You need to specify which HTTP methods are allowed for the files');\n }\n\n const methods = Object.keys(options.methods) as RouterMethod[];\n\n const atLeastOne = methods.some((method) => options.methods[method]);\n if (!atLeastOne) {\n throw new Error('You need to enable at least one HTTP method to serve the files');\n }\n\n const allowedMethods: RouterMethod[] = [\n 'all',\n 'get',\n 'head',\n 'post',\n 'patch',\n 'put',\n 'delete',\n 'connect',\n 'options',\n 'trace',\n ];\n\n const invalid = methods.find(\n (method) => !allowedMethods.includes(method.toLowerCase() as RouterMethod),\n );\n\n if (invalid) {\n throw new Error(`${invalid} is not a valid HTTP method`);\n }\n\n const newMethods = methods.reduce<Record<string, boolean>>((acc, method) => {\n acc[method.toLowerCase()] = !!options.methods[method];\n return acc;\n }, {});\n\n return {\n ...options,\n methods: newMethods,\n };\n }\n /**\n * Parses the files received from the constructor's options, and formats them into\n * proper definitions the controller can use.\n */\n protected _createFiles(): Record<string, StaticsControllerFile> {\n const { files, paths } = this._options;\n const routePath = removeSlashes(paths.route, false, true);\n return files.reduce<Record<string, StaticsControllerFile>>((acc, file) => {\n let src;\n let route;\n let headers;\n if (typeof file === 'object') {\n ({ route, path: src, headers } = file);\n } else {\n src = file;\n route = file;\n }\n\n src = path.join(paths.source, src);\n route = removeSlashes(route, true, false);\n route = `${routePath}/${route}`;\n acc[route] = {\n path: src,\n route,\n headers: headers || {},\n };\n\n return acc;\n }, {});\n }\n}\n/**\n * A controller that allows the application to server specific files from any folder to\n * any route without the need of mounting directories as \"static\" folders.\n *\n * @group Controllers\n * @group Controllers/Statics\n */\nexport const staticsController = controllerCreator(\n ({ getMiddlewares, ...options }: StaticsControllerCreatorOptions = {}) =>\n (app) => {\n const router = app.getRouter();\n const ctrl = new StaticsController({\n inject: {\n sendFile: app.get('sendFile'),\n },\n ...options,\n });\n\n let useMiddlewares: ExpressMiddleware[] | undefined;\n if (getMiddlewares) {\n useMiddlewares = getMiddlewares(app)\n .map((middleware) => {\n if ('middleware' in middleware) {\n return middleware.connect(app) as ExpressMiddleware | undefined;\n }\n\n return middleware as ExpressMiddleware;\n })\n .filter(notUndefined);\n }\n\n return ctrl.addRoutes(router, useMiddlewares);\n },\n);\n"],"mappings":";;;AAAA,YAAY,UAAU;AACtB,YAAY,UAAU;AACtB,SAAS,+BAA+B;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAwIA,MAAM,kBAAkB;AAAA;AAAA;AAAA;AAAA,EAiB7B,YAAY,EAAE,QAAQ,GAAG,QAAQ,GAAwC;AAbzE;AAAA;AAAA;AAAA,wBAAmB;AAInB;AAAA;AAAA;AAAA,wBAAU;AAKV;AAAA;AAAA;AAAA;AAAA,wBAAU;AAKR,SAAK,YAAY,OAAO;AACxB,SAAK,WAAW,KAAK;AAAA,MACnB;AAAA,QACE;AAAA,UACE,OAAO,CAAC,eAAe,YAAY;AAAA,UACnC,SAAS,QAAQ,WAAW;AAAA,YAC1B,KAAK;AAAA,YACL,KAAK;AAAA,UACP;AAAA,UACA,OAAO;AAAA,YACL,OAAO;AAAA,YACP,Q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../../src/controllers/common/statics.ts"],"sourcesContent":["import * as path from 'path';\nimport type mime from 'mime';\nimport { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport {\n controllerCreator,\n removeSlashes,\n notUndefined,\n type MiddlewareLike,\n} from '../../utils';\nimport type { SendFile } from '../../services';\nimport type { Jimpex } from '../../app';\nimport type { DeepPartial, ExpressMiddleware, Router, RouterMethod } from '../../types';\n\ntype Mime = typeof mime;\n\n/**\n * The definition for each file the controller handles.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerFile = {\n /**\n * The route, relative to the controller root, to the file.\n */\n route: string;\n /**\n * The path to the file in the filesystem. Since the file is served using the\n * {@link SendFile} service, whether the file is relative to the project root or the\n * application executable depends on how the service is configured (relative to the\n * executable by default).\n */\n path: string;\n /**\n * A dictionary of headers for the response.\n */\n headers?: Record<string, string>;\n};\n/**\n * These are like \"master paths\" that get prepended to all the file paths and routes the\n * controller use.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerPathsOptions = {\n /**\n * A custom route to prefix all the file routes with.\n */\n route: string;\n /**\n * A custom path to prefix all the file paths with.\n */\n source: string;\n};\n/**\n * The options to customize the controller.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerOptions = {\n /**\n * A list of filenames, or definitions for the files to handle.\n */\n files: Array<string | StaticsControllerFile>;\n /**\n * A dictionary with the allowed router (HTTP) methods the controller can use to serve\n * the files. If `all` is set to `true`, the rest of the values will be ignored.\n *\n * @default {get: true, all: false}\n */\n methods: Partial<Record<RouterMethod, boolean>>;\n /**\n * The \"master paths\" the controller can use to prefix the file paths and routes.\n *\n * @default {route: '', source: './',}\n */\n paths: StaticsControllerPathsOptions;\n};\n/**\n * The options to construct a {@link StaticsController}.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerConstructorOptions =\n DeepPartial<StaticsControllerOptions> & {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n sendFile: SendFile;\n mime: Mime;\n };\n };\n/**\n * A function to generate a list of middlewares that can be executed before the tontroller\n * main middleware.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerGetMiddlewaresFn = (app: Jimpex) => MiddlewareLike[];\n/**\n * The options for the controller creator that mounts {@link StaticsController}.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerCreatorOptions = DeepPartial<StaticsControllerOptions> & {\n /**\n * A function to generate a list of middlewares that can be executed before the\n * tontroller main middleware.\n */\n getMiddlewares?: StaticsControllerGetMiddlewaresFn;\n};\n/**\n * The options for {@link StaticsController._addRoute}.\n *\n * @access protected\n * @group Controllers/Statics\n */\nexport type AddStaticRouteOptions = {\n /**\n * The reference for the router in which the middlewares will be added.\n */\n router: Router;\n /**\n * The router method in which the middlewares will be added.\n */\n method: RouterMethod;\n /**\n * The definition of the file to serve.\n */\n file: StaticsControllerFile;\n /**\n * The middleware created by {@link StaticsController}, that will serve the file.\n */\n fileMiddleware: ExpressMiddleware;\n /**\n * A list of extra middlewares to execute before the file middleware.\n */\n middlewares: ExpressMiddleware[];\n};\n\n/**\n * The controller class that allows the application to serve specific files from any\n * folder to any route without the need of mounting directories as \"static\".\n *\n * @group Controller Classes\n * @group Controllers/Statics\n * @prettierignore\n */\nexport class StaticsController {\n /**\n * The service that serves static files.\n */\n protected readonly _sendFile: SendFile;\n /**\n * The MIME type library. Since it's an ESM only module, Jimpex loads it on boot and makes\n * it available on the container.\n */\n protected readonly _mime: Mime;\n /**\n * The controller customization options.\n */\n protected _options: StaticsControllerOptions;\n /**\n * A dictionary with the formatted definitions of the files that will be served.\n * It uses the files' routes as keys, for easy access in the middleware.\n */\n protected files: Record<string, StaticsControllerFile>;\n /**\n * @param options The options to construct the controller.\n */\n constructor({ inject, ...options }: StaticsControllerConstructorOptions) {\n this._sendFile = inject.sendFile;\n this._mime = inject.mime;\n this._options = this._validateOptions(\n deepAssignWithOverwrite(\n {\n files: ['favicon.ico', 'index.html'],\n methods: options.methods || {\n all: false,\n get: true,\n },\n paths: {\n route: '',\n source: './',\n },\n },\n options,\n ),\n );\n this.files = this._createFiles();\n }\n /**\n * Mounts the middlewares in the router in order to serve the files.\n *\n * @param router A reference to the application router.\n * @param middlewares A list of extra middlewares to execute before the file\n * middleware.\n */\n addRoutes(router: Router, middlewares: ExpressMiddleware[] = []): Router {\n const { methods } = this._options;\n const use: RouterMethod[] = methods.all\n ? ['all']\n : Object.keys(methods).reduce<RouterMethod[]>((acc, name) => {\n const methodName = name as RouterMethod;\n if (methods[methodName]) {\n acc.push(methodName);\n }\n\n return acc;\n }, []);\n\n Object.keys(this.files).forEach((route) => {\n const file = this.files[route as keyof typeof this.files]!;\n const fileMiddleware = this._getMiddleware(file);\n use.forEach((method) =>\n this._addRoute({ router, method, file, fileMiddleware, middlewares }),\n );\n });\n\n return router;\n }\n /**\n * The controller options.\n */\n get options(): Readonly<StaticsControllerOptions> {\n return { ...this._options };\n }\n /**\n * Generates the middleware that will serve the file.\n *\n * @param file The definition of the file to serve.\n */\n protected _getMiddleware(file: StaticsControllerFile): ExpressMiddleware {\n return (_, res, next) => {\n const extension = path.parse(file.path).ext.substring(1);\n const headers = {\n 'Content-Type': this._mime.getType(extension) || 'text/html',\n ...file.headers,\n };\n\n Object.entries(headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n\n this._sendFile({\n res,\n filepath: file.path,\n next,\n });\n };\n }\n /**\n * Mounts the middleware(s) for a file in the router.\n *\n * @param options The information of the file and how it needs to be added.\n */\n protected _addRoute({\n router,\n method,\n file,\n fileMiddleware,\n middlewares,\n }: AddStaticRouteOptions): void {\n const { route } = file;\n router[method](route, [...middlewares, fileMiddleware]);\n }\n /**\n * Validates and formats the options sent to the constructor in order to get the final\n * set that will be stored in the controller.\n *\n * @param options The options to validate.\n * @throws If no files are specified.\n * @throws If methods is not defined.\n * @throws If no methods are enabled.\n * @throws If there's an invalid HTTP method.\n */\n protected _validateOptions(\n options: StaticsControllerOptions,\n ): StaticsControllerOptions {\n if (!options.files || !options.files.length) {\n throw new Error('You need to specify a list of files');\n }\n\n if (!options.methods) {\n throw new Error('You need to specify which HTTP methods are allowed for the files');\n }\n\n const methods = Object.keys(options.methods) as RouterMethod[];\n\n const atLeastOne = methods.some((method) => options.methods[method]);\n if (!atLeastOne) {\n throw new Error('You need to enable at least one HTTP method to serve the files');\n }\n\n const allowedMethods: RouterMethod[] = [\n 'all',\n 'get',\n 'head',\n 'post',\n 'patch',\n 'put',\n 'delete',\n 'connect',\n 'options',\n 'trace',\n ];\n\n const invalid = methods.find(\n (method) => !allowedMethods.includes(method.toLowerCase() as RouterMethod),\n );\n\n if (invalid) {\n throw new Error(`${invalid} is not a valid HTTP method`);\n }\n\n const newMethods = methods.reduce<Record<string, boolean>>((acc, method) => {\n acc[method.toLowerCase()] = !!options.methods[method];\n return acc;\n }, {});\n\n return {\n ...options,\n methods: newMethods,\n };\n }\n /**\n * Parses the files received from the constructor's options, and formats them into\n * proper definitions the controller can use.\n */\n protected _createFiles(): Record<string, StaticsControllerFile> {\n const { files, paths } = this._options;\n const routePath = removeSlashes(paths.route, false, true);\n return files.reduce<Record<string, StaticsControllerFile>>((acc, file) => {\n let src;\n let route;\n let headers;\n if (typeof file === 'object') {\n ({ route, path: src, headers } = file);\n } else {\n src = file;\n route = file;\n }\n\n src = path.join(paths.source, src);\n route = removeSlashes(route, true, false);\n route = `${routePath}/${route}`;\n acc[route] = {\n path: src,\n route,\n headers: headers || {},\n };\n\n return acc;\n }, {});\n }\n}\n/**\n * A controller that allows the application to server specific files from any folder to\n * any route without the need of mounting directories as \"static\" folders.\n *\n * @group Controllers\n * @group Controllers/Statics\n */\nexport const staticsController = controllerCreator(\n ({ getMiddlewares, ...options }: StaticsControllerCreatorOptions = {}) =>\n (app) => {\n const router = app.getRouter();\n const ctrl = new StaticsController({\n inject: {\n sendFile: app.get('sendFile'),\n mime: app.get('mime'),\n },\n ...options,\n });\n\n let useMiddlewares: ExpressMiddleware[] | undefined;\n if (getMiddlewares) {\n useMiddlewares = getMiddlewares(app)\n .map((middleware) => {\n if ('middleware' in middleware) {\n return middleware.connect(app) as ExpressMiddleware | undefined;\n }\n\n return middleware as ExpressMiddleware;\n })\n .filter(notUndefined);\n }\n\n return ctrl.addRoutes(router, useMiddlewares);\n },\n);\n"],"mappings":";;;AAAA,YAAY,UAAU;AAEtB,SAAS,+BAA+B;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AA4IA,MAAM,kBAAkB;AAAA;AAAA;AAAA;AAAA,EAsB7B,YAAY,EAAE,QAAQ,GAAG,QAAQ,GAAwC;AAlBzE;AAAA;AAAA;AAAA,wBAAmB;AAKnB;AAAA;AAAA;AAAA;AAAA,wBAAmB;AAInB;AAAA;AAAA;AAAA,wBAAU;AAKV;AAAA;AAAA;AAAA;AAAA,wBAAU;AAKR,SAAK,YAAY,OAAO;AACxB,SAAK,QAAQ,OAAO;AACpB,SAAK,WAAW,KAAK;AAAA,MACnB;AAAA,QACE;AAAA,UACE,OAAO,CAAC,eAAe,YAAY;AAAA,UACnC,SAAS,QAAQ,WAAW;AAAA,YAC1B,KAAK;AAAA,YACL,KAAK;AAAA,UACP;AAAA,UACA,OAAO;AAAA,YACL,OAAO;AAAA,YACP,QAAQ;AAAA,UACV;AAAA,QACF;AAAA,QACA;AAAA,MACF;AAAA,IACF;AACA,SAAK,QAAQ,KAAK,aAAa;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,UAAU,QAAgB,cAAmC,CAAC,GAAW;AACvE,UAAM,EAAE,QAAQ,IAAI,KAAK;AACzB,UAAM,MAAsB,QAAQ,MAChC,CAAC,KAAK,IACN,OAAO,KAAK,OAAO,EAAE,OAAuB,CAAC,KAAK,SAAS;AACzD,YAAM,aAAa;AACnB,UAAI,QAAQ,UAAU,GAAG;AACvB,YAAI,KAAK,UAAU;AAAA,MACrB;AAEA,aAAO;AAAA,IACT,GAAG,CAAC,CAAC;AAET,WAAO,KAAK,KAAK,KAAK,EAAE,QAAQ,CAAC,UAAU;AAC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AI,KAAK;AAC7B,UAAI,KAAK,IAAI;AAAA,QACX,MAAM;AAAA,QACN;AAAA,QACA,SAAS,WAAW,CAAC;AAAA,MACvB;AAEA,aAAO;AAAA,IACT,GAAG,CAAC,CAAC;AAAA,EACP;AACF;AAQO,MAAM,oBAAoB;AAAA,EAC/B,CAAC,EAAE,gBAAgB,GAAG,QAAQ,IAAqC,CAAC,MAClE,CAAC,QAAQ;AACP,UAAM,SAAS,IAAI,UAAU;AAC7B,UAAM,OAAO,IAAI,kBAAkB;AAAA,MACjC,QAAQ;AAAA,QACN,UAAU,IAAI,IAAI,UAAU;AAAA,QAC5B,MAAM,IAAI,IAAI,MAAM;AAAA,MACtB;AAAA,MACA,GAAG;AAAA,IACL,CAAC;AAED,QAAI;AACJ,QAAI,gBAAgB;AAClB,uBAAiB,eAAe,GAAG,EAChC,IAAI,CAAC,eAAe;AACnB,YAAI,gBAAgB,YAAY;AAC9B,iBAAO,WAAW,QAAQ,GAAG;AAAA,QAC/B;AAEA,eAAO;AAAA,MACT,CAAC,EACA,OAAO,YAAY;AAAA,IACxB;AAEA,WAAO,KAAK,UAAU,QAAQ,cAAc;AAAA,EAC9C;AACJ;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
__publicField
|
|
3
|
-
} from "../../chunk-
|
|
3
|
+
} from "../../chunk-F3FYYIAV.js";
|
|
4
4
|
import { deepAssignWithOverwrite } from "@homer0/deep-assign";
|
|
5
5
|
import { flat, unflat } from "@homer0/object-utils";
|
|
6
6
|
import {
|
|
@@ -228,6 +228,9 @@ class GatewayController {
|
|
|
228
228
|
...helperBasePayload
|
|
229
229
|
});
|
|
230
230
|
if (shouldStream) {
|
|
231
|
+
if (response.body === null) {
|
|
232
|
+
throw new Error("The response body is null");
|
|
233
|
+
}
|
|
231
234
|
res.status(response.status);
|
|
232
235
|
response.headers.forEach((value, name) => {
|
|
233
236
|
if (!headersOptions.remove.includes(name)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/controllers/utils/gateway.ts"],"sourcesContent":["import { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport { flat, unflat } from '@homer0/object-utils';\nimport type { APIClientOptions } from '@homer0/api-utils';\nimport {\n controllerProviderCreator,\n controller,\n createRouteExpression,\n removeSlashes,\n notUndefined,\n type MiddlewareLike,\n} from '../../utils';\nimport type { HTTP, HTTPFetchOptions } from '../../services';\nimport type { Jimpex } from '../../app';\nimport {\n RouterMethod,\n DeepPartial,\n Request,\n Response,\n NextFunction,\n HTTPResponse,\n Router,\n ExpressMiddleware,\n AsyncExpressMiddleware,\n} from '../../types';\n/**\n * The extended definition for endpoints.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfigEndpointProps = {\n /**\n * The path to the endpoint relative to the entry point. It can include placeholders for\n * parameters like `/:parameter/`.\n */\n path: string;\n /**\n * The router (HTTP) method for the endpoint.\n *\n * @default 'all'\n */\n method?: RouterMethod;\n};\n/**\n * The definition of an endpoint: it can be just the path, relative to the entry point, or\n * an object in which you can also specify things like the method.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfigEndpointDefinition = string | GatewayConfigEndpointProps;\n/**\n * The dictionary of endpoints the controller uses. The reason for this type is that this\n * could be a flat dictionary, or a nested one.\n *\n * @example\n *\n * <caption>A flat dictionary</caption>\n *\n * {\n * random: '/random',\n * users: '/users',\n * userById: {\n * path: '/users/:id',\n * method: 'get',\n * },\n * }\n *\n * @example\n *\n * <caption>A nested dictionary</caption>\n *\n * {\n * random: '/random',\n * users: {\n * list: '/users',\n * byId: {\n * path: '/users/:id',\n * method: 'get',\n * },\n * },\n * }\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfigEndpoints = {\n [key: string]: GatewayConfigEndpointDefinition | GatewayConfigEndpoints;\n};\n/**\n * The configuration for the gateway the controller uses.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfig = {\n /**\n * The entry point to the API the controller will make the requests to.\n */\n url: string;\n /**\n * The dictionary of enpoints the gateway will make available.\n */\n gateway: GatewayConfigEndpoints;\n};\n/**\n * The options for how the gateway will handle the headers from the requests and the\n * responses.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerHeaderOptions = {\n /**\n * Whether or not to include the header with the request's IP address.\n *\n * @default true\n */\n useXForwardedFor: boolean;\n /**\n * Whether or not to copy all custom headers from the request. By custom header, it\n * means all the headers which names start with `x-`.\n *\n * @default true\n */\n copyCustomHeaders: boolean;\n /**\n * A list of \"known\" headers the gateway will try to copy from the incoming request.\n *\n * @default ['authorization','content-type', 'referer', 'user-agent']\n */\n copy: string[];\n /**\n * A list of \"known\" headers the gateway will try to remove the response.\n *\n * @default ['server', 'x-powered-by']\n */\n remove: string[];\n};\n/**\n * The extra options for the gateway controller. They are \"extra\" because they are mostly\n * helpers for when used with an API client, or for optional features.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerExtraOptions = {\n /**\n * This is really a helper for when the gateway is used with an API client. The idea is\n * that, by default, the routes are mounted on the controller route, but with this\n * option, you can specify another sub path. For example: The controller is mounted on\n * `/routes`, and if you set `root` to `gateway`, all the routes will be on\n * `/routes/gateway`.\n *\n * This become important (and useful) when you get the API client configuration (with\n * `getAPIConfig`): The `url` will be the controller route, but all the endpoints will\n * be modified and prefixed with the `root`, that way, you can have multiple gateways in\n * the same \"base route\".\n *\n * It can also includes placeholders for parameters like `/:parameter/`, that will be\n * replaced with the `placeholders` option when `getAPIConfig` gets called.\n *\n * @default ''\n */\n root: string;\n /**\n * This is another option for when the gateway is used with an API client. When calling\n * `getAPIConfig`, all the endpoints will be wrapped inside an object named after this\n * option. For example: `{ url: '...', endpoints: { api: { ... } } }`.\n *\n * @default 'api'\n */\n apiConfigSetting: string;\n /**\n * The options for how the gateway will handle the headers from the requests and the\n * responses.\n */\n headers: GatewayControllerHeaderOptions;\n};\n/**\n * The required options for the gateway controller.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerOptions = {\n /**\n * The configuration for the API the gateway will make the requests to.\n */\n gatewayConfig: GatewayConfig;\n /**\n * The route where the controller is mounted.\n */\n route: string;\n} & DeepPartial<GatewayControllerExtraOptions>;\n/**\n * The information for a request the controller will make.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerRequest = {\n /**\n * The URL for the request.\n */\n url: string;\n /**\n * The options for the fetch client that will make the requests.\n */\n options: HTTPFetchOptions;\n};\n/**\n * The information for an endpoint the gateway is calling.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerEndpointInfo = {\n /**\n * The name of the endpoint in the configuration.\n */\n name: string;\n /**\n * The properties (path and method) of the endpoint.\n */\n definition: GatewayConfigEndpointDefinition;\n};\n/**\n * These are the base options sent to all the helper service functions.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceBaseFnOptions = {\n /**\n * The information of the endpoint the gateway is calling.\n */\n endpoint: GatewayControllerEndpointInfo;\n /**\n * The request recived by the application.\n */\n req: Request;\n /**\n * The response object created by the application.\n */\n res: Response;\n /**\n * The function to call the next middleware in the chain.\n */\n next: NextFunction;\n};\n/**\n * The information sent to the helper service in order to modify, or not, a request before\n * it is sent.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceRequestReducerOptions =\n GatewayHelperServiceBaseFnOptions & {\n /**\n * The options the controller created for the fetch client.\n */\n endpointReq: GatewayControllerRequest;\n };\n/**\n * A function that can be used to modify the information of an endpoint before making a\n * request.\n *\n * @param options The information of the request.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceRequestReducer = (\n options: GatewayHelperServiceRequestReducerOptions,\n) => Promise<GatewayControllerRequest>;\n/**\n * The information sent to the helper service in order to modify a response before\n * processing it, decide if it should be streamed or not, and even handle it.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceResponseReducerOptions =\n GatewayHelperServiceBaseFnOptions & {\n /**\n * The response from the endpoint request.\n */\n endpointRes: HTTPResponse;\n };\n/**\n * A function that can be used to modify the response of an endpoint before the controller\n * processes it.\n *\n * @param options The information of the response.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceResponseReducer = (\n options: GatewayHelperServiceResponseReducerOptions,\n) => Promise<HTTPResponse>;\n/**\n * A function that can be used to tell the controller to stream the response of an\n * endpoint or not.\n * If it returns `false`, the function to handle responses should be defined, otherwise,\n * an error will be generated.\n *\n * @param options The information of the response.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceStreamVerification = (\n options: GatewayHelperServiceResponseReducerOptions,\n) => Promise<boolean>;\n/**\n * A function to handle the response of an endpoint. This is called when the helper\n * service tells the controller that the endpoint shouldn't be streamed, so this method\n * should handle the response.\n *\n * @param options The information of the response.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceResponseHandler = (\n options: GatewayHelperServiceResponseReducerOptions,\n) => Promise<void>;\n/**\n * The information sent to the helper service in order to handle a failed request for an\n * endpoint.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceErrorHandlerOptions =\n GatewayHelperServiceBaseFnOptions & {\n /**\n * The error generated during the request.\n */\n error: Error;\n };\n/**\n * A function to handle the error of an endpoint request.\n *\n * @param options The information of the error.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceErrorHandler = (\n options: GatewayHelperServiceErrorHandlerOptions,\n) => void;\n/**\n * The interface of a helper service that can intercept/modify the requests and responses\n * the gateway makes.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperService = Partial<{\n /**\n * A function that is called before an endpoint request is made.\n */\n reduceEndpointRequest: GatewayHelperServiceRequestReducer;\n /**\n * A function that is called with the response of an endpoint request.\n */\n reduceEndpointResponse: GatewayHelperServiceResponseReducer;\n /**\n * A function called in order to validate if an endpoint response should be streamed or\n * not. If the function returns `false`, `handleEndpointResponse` will be called.\n */\n shouldStreamEndpointResponse: GatewayHelperServiceStreamVerification;\n /**\n * A function called when `shouldStreamEndpointResponse` returns `false`. The function\n * should handle the response for the application.\n */\n handleEndpointResponse: GatewayHelperServiceResponseHandler;\n /**\n * A function called when an error is generated during an endpoint request/processing.\n */\n handleEndpointError: GatewayHelperServiceErrorHandler;\n}>;\n/**\n * Utility type for the options object sent to the \"proxy methods\" the controller has for\n * the helper service.\n *\n * @template T The type of the options for a specific helper service function.\n * @access protected\n * @group Controllers/Gateway\n */\nexport type GatewayControllerHelperOptions<T> = T & {\n /**\n * The reference for the helper service.\n */\n helper: GatewayHelperService;\n};\n/**\n * The information for a single HTTP method an endpoint can handle.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerRouteMethod = {\n /**\n * The method for the route.\n */\n method: RouterMethod;\n /**\n * The information of the endpoint.\n */\n endpoint: GatewayControllerEndpointInfo;\n};\n/**\n * The information for all the HTTP methods that can be handled for an endpoint.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerRoute = {\n /**\n * The path to the endpoint, relative to the entry point.\n */\n path: string;\n /**\n * The path for the route in the controller. This is different from `path` as it's possible for\n * the gateway to be implemented using the `root` option.\n */\n route: string;\n /**\n * A list with all the methods the controller uses on the route.\n */\n methods: GatewayControllerRouteMethod[];\n};\n/**\n * The API client configuration the gateway can generate for its endpoints.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerAPIConfig = {\n /**\n * The base URL for the API.\n */\n url: string;\n /**\n * The dictionary of endpoints the controller handles.\n */\n endpoints: APIClientOptions['endpoints'];\n};\n/**\n * The options sent to {@link GatewayController.getAPIConfig}.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerAPIConfigOptions = {\n /**\n * This can be used to overwrite the gateway's `apiConfigSetting` option, and set a new\n * setting as a wrapper for the endpoints.\n */\n setting?: string;\n /**\n * A dictionary of values for possible placeholders that were sent using the `root`\n * option.\n */\n placeholders?: Record<string, string>;\n};\n/**\n * The options to construct a {@link GatewayController}.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerConstructorOptions = GatewayControllerOptions & {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n http: HTTP;\n /**\n * A function to get a possible helper service. This is injected as a \"getter\" to not\n * interrupt the DIC \"lifecycle\": controllers are initialized right when the app\n * starts, and injecting a reference would force the service to be initialized too,\n * even if a request is not being made.\n */\n getHelperService?: () => GatewayHelperService | undefined;\n };\n};\n/**\n * The options for {@link GatewayController._addRoute}.\n *\n * @access protected\n * @group Controllers/Gateway\n */\nexport type AddGatewayRouteOptions = {\n /**\n * The reference for the router in which the middlewares will be added.\n */\n router: Router;\n /**\n * The router method in which the middlewares will be added.\n */\n method: RouterMethod;\n /**\n * The route in which the middlewares will be added.\n */\n route: string;\n /**\n * The middleware created by {@link GatewayController}, that makes the request.\n */\n gatewayMiddleware: AsyncExpressMiddleware;\n /**\n * A list of extra middlewares to prepend to the gateway middleware.\n */\n middlewares: ExpressMiddleware[];\n};\n/**\n * A utility controller that generates routes that act as a gateway for a specific API.\n *\n * @group Controller Classes\n * @group Controllers/Gateway\n * @prettierignore\n */\nexport class GatewayController {\n /**\n * The service that makes HTTP requests.\n */\n protected readonly http: HTTP;\n /**\n * A function to get a possible helper service. This is injected as a \"getter\" to not\n * interrupt the DIC \"lifecycle\": controllers are initialized right when the app\n * starts, and injecting a reference would force the service to be initialized too,\n * even if a request is not being made.\n */\n protected readonly _getHelperService: () => GatewayHelperService | undefined;\n /**\n * The information, url and endpoints, for the gateway the controller will make requests to.\n */\n protected readonly _gatewayConfig: GatewayConfig;\n /**\n * The route in which the controller is mounted.\n */\n protected readonly _route: string;\n /**\n * A regular expression that will be used to remove the controller route from a\n * request path. This will allow the main middleware to extract the path to where the\n * request should be made.\n */\n protected readonly _routeExpression: RegExp;\n /**\n * The controller customization options.\n */\n protected readonly _options: GatewayControllerExtraOptions;\n /**\n * A flat dictionary with the endpoints information.\n */\n protected readonly _endpoints: Record<string, GatewayConfigEndpointDefinition>;\n /**\n * The entry URL for the API client configuration the controller can generate.\n */\n protected readonly _apiConfigUrl: string;\n /**\n * The generated endpoints for the API client configuration the controller can generate.\n */\n protected readonly _apiConfigEndpoints: APIClientOptions['endpoints'];\n /**\n * The list of routes the controller can handle.\n */\n protected readonly _routes: GatewayControllerRoute[];\n /**\n * @param options The options to construct the controller.\n */\n constructor({\n inject,\n route,\n gatewayConfig,\n ...options\n }: GatewayControllerConstructorOptions) {\n this.http = inject.http;\n this._getHelperService = inject.getHelperService || (() => undefined);\n this._route = removeSlashes(route);\n this._options = this._formatOptions(\n deepAssignWithOverwrite(\n {\n root: '',\n apiConfigSetting: 'api',\n headers: {\n useXForwardedFor: true,\n copyCustomHeaders: true,\n copy: ['authorization', 'content-type', 'referer', 'user-agent'],\n remove: ['server', 'x-powered-by', 'content-encoding'],\n },\n },\n options,\n ),\n );\n this._gatewayConfig = {\n ...gatewayConfig,\n url: removeSlashes(gatewayConfig.url, false, true),\n };\n this._routeExpression = createRouteExpression(\n this._options.root ? `${this._route}/${this._options.root}` : this._route,\n true,\n true,\n );\n this._endpoints = this._formatEndpoints();\n this._routes = this._createRoutes();\n const { url, endpoints } = this._createAPIConfig();\n this._apiConfigUrl = url;\n this._apiConfigEndpoints = endpoints;\n }\n /**\n * Generates an API client configuration based on the controller routes.\n *\n * @param options The options to customize the generated configuration.\n */\n getAPIConfig({\n setting,\n placeholders = {},\n }: GatewayControllerAPIConfigOptions = {}): Readonly<GatewayControllerAPIConfig> {\n const useSetting = setting || this._options.apiConfigSetting;\n let url: string;\n const placeholdersEntries = Object.entries(placeholders);\n if (placeholdersEntries.length) {\n url = placeholdersEntries.reduce<string>(\n (acc, [key, value]) => acc.replace(`:${key}`, value),\n this._apiConfigUrl,\n );\n } else {\n url = this._apiConfigUrl;\n }\n\n return {\n url,\n endpoints: {\n [useSetting]: this._apiConfigEndpoints,\n },\n };\n }\n /**\n * Mounts the middlewares in the router in order to make the requests.\n *\n * @param router A reference to the application router.\n * @param middlewares A list of extra middlewares to execute before the gateway\n * middleware.\n */\n addRoutes(router: Router, middlewares: ExpressMiddleware[] = []): Router {\n this._routes.forEach((route) => {\n route.methods.forEach((info) => {\n this._addRoute({\n router,\n method: info.method,\n route: route.route,\n gatewayMiddleware: this._createGatewayMiddleware(info.endpoint),\n middlewares,\n });\n });\n });\n\n return router;\n }\n /**\n * The customization options.\n */\n get options(): Readonly<GatewayControllerExtraOptions> {\n return { ...this._options };\n }\n /**\n * The configuration for the gateway the controller will make requests to.\n */\n get gatewayConfig(): Readonly<GatewayConfig> {\n return { ...this._gatewayConfig };\n }\n /**\n * Generates a middleware that will make the request to an endpoint and stream the\n * response.\n *\n * @param endpoint The information of the endpoint the middleware will handle.\n */\n protected _createGatewayMiddleware(\n endpoint: GatewayControllerEndpointInfo,\n ): AsyncExpressMiddleware {\n return async (req, res, next) => {\n const {\n _options: { headers: headersOptions },\n _gatewayConfig: { url: gatewayUrl },\n _routeExpression: routeExpression,\n } = this;\n // Remove the controller route from the requested URL.\n const reqPath = req.originalUrl.replace(routeExpression, '');\n // Process the headers for the request.\n let headers: Record<string, string> = {};\n // - Copy the headers from the incoming request.\n headersOptions.copy.forEach((name) => {\n if (req.headers[name]) {\n headers[name] = req.headers[name] as string;\n }\n });\n // - Copy the custom headers.\n if (headersOptions.copyCustomHeaders) {\n headers = deepAssignWithOverwrite<Record<string, string>>(\n headers,\n this.http.getCustomHeadersFromRequest(req),\n );\n }\n // - Include the IP on the X-Forwarded-For header, if enabled.\n if (headersOptions.useXForwardedFor) {\n const ip = this.http.getIPFromRequest(req);\n if (ip) {\n headers['x-forwarded-for'] = ip;\n }\n }\n\n const method = req.method.toUpperCase();\n // If the request has a body and the method is not `GET`, stringify it.\n let body: string | undefined;\n if (method !== 'GET' && typeof req.body === 'object') {\n body = JSON.stringify(req.body);\n // If there's no `content-type`, let's assume it's JSON.\n if (!headers['content-type']) {\n headers['content-type'] = 'application/json';\n }\n }\n\n /**\n * Get the helper service, if there's one, and define the base options for its\n * methods.\n */\n const helper = this._getHelperService() || {};\n const helperBasePayload = {\n endpoint,\n req,\n res,\n next,\n helper,\n };\n\n try {\n // Reduce the request information before using it.\n const request = await this._reduceEndpointRequest({\n endpointReq: {\n url: `${gatewayUrl}/${reqPath}`,\n options: {\n method,\n headers,\n body,\n },\n },\n ...helperBasePayload,\n });\n // Make the actual request.\n const responseRaw = await this.http.fetch(request.url, request.options);\n // Reduce the response information before using it.\n const response = await this._reduceEndpointResponse({\n endpointRes: responseRaw,\n ...helperBasePayload,\n });\n // Validate if the response should be streamed.\n const shouldStream = await this._shouldStreamEndpointResponse({\n endpointRes: responseRaw,\n ...helperBasePayload,\n });\n\n if (shouldStream) {\n /**\n * If the response should be streamed, set the status, remove unwanted headers,\n * and pipe it to the application response object.\n */\n res.status(response.status);\n response.headers.forEach((value, name) => {\n if (!headersOptions.remove.includes(name)) {\n res.setHeader(name, value);\n }\n });\n\n response.body.pipe(res).on('error', (error) => {\n next(error);\n });\n } else {\n /**\n * If the response should not be streamed, send it to the helper method to\n * handle it.\n */\n await this._handleEndpointResponse({\n endpointRes: response,\n ...helperBasePayload,\n });\n }\n } catch (error) {\n // Something failed, so let's pass the error to the helper service.\n this._handleEndpointError({\n error: error as Error,\n ...helperBasePayload,\n });\n }\n };\n }\n /**\n * Mounts the middleware(s) for an endpoint in the router.\n *\n * @param options The information of the endpoint and how it needs to be added.\n */\n protected _addRoute({\n router,\n method,\n route,\n gatewayMiddleware,\n middlewares,\n }: AddGatewayRouteOptions): void {\n router[method](route, [...middlewares, gatewayMiddleware]);\n }\n /**\n * Formats the endpoints for the gateway into a flat dictionary without nesting.\n */\n protected _formatEndpoints(): Record<string, GatewayConfigEndpointDefinition> {\n return flat({\n target: this._gatewayConfig.gateway,\n shouldFlatten: (_, value) => {\n const useValue = value as { path?: string };\n return typeof useValue.path === 'undefined';\n },\n });\n }\n /**\n * Based on the information from the endpoints, this method will create the routes the\n * controller will later add on a router.\n *\n * @throws If there's more than one endpoint using the same path with the same HTTP\n * method.\n */\n protected _createRoutes(): GatewayControllerRoute[] {\n const routes: Record<\n string,\n {\n path: string;\n methods: Partial<Record<RouterMethod, string>>;\n }\n > = {};\n Object.keys(this._endpoints).forEach((name) => {\n const endpoint = this._endpoints[name]!;\n let endpointPath: string;\n let endpointMethod: RouterMethod;\n if (typeof endpoint === 'string') {\n endpointPath = endpoint;\n endpointMethod = 'all';\n } else {\n endpointPath = endpoint.path;\n endpointMethod = endpoint.method\n ? this._validateHTTPMethod(endpoint.method)\n : 'all';\n }\n\n endpointPath = removeSlashes(endpointPath);\n if (!routes[endpointPath]) {\n routes[endpointPath] = {\n path: endpointPath,\n methods: {},\n };\n }\n\n if (routes[endpointPath]!.methods[endpointMethod]) {\n const repeatedEndpoint = routes[endpointPath]!.methods[endpointMethod];\n throw new Error(\n \"You can't have two gateway endpoints to the same path and with the same \" +\n `HTTP method: '${repeatedEndpoint}' and '${name}'`,\n );\n }\n\n routes[endpointPath]!.methods[endpointMethod] = name;\n });\n\n const routePrefixes = this._options.root ? `/${this._options.root}/` : '/';\n return Object.keys(routes).map((endpointPath) => {\n const info = routes[endpointPath]!;\n return {\n path: info.path,\n route: `${routePrefixes}${info.path}`,\n methods: Object.keys(info.methods).map((methodNameRaw) => {\n const methodName = methodNameRaw as RouterMethod;\n const endpointName = info.methods[methodName]!;\n const endpointDefinition = this._endpoints[endpointName]!;\n return {\n method: methodName,\n endpoint: {\n name: endpointName,\n definition: endpointDefinition,\n },\n };\n }),\n };\n });\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that can modify an\n * endpoint request before it gets made.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `reduceEndpointRequest`, it will just return\n * information for the request.\n *\n * @param options The information of the request and the reference to the helper.\n */\n protected _reduceEndpointRequest({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceRequestReducerOptions>): Promise<GatewayControllerRequest> {\n if (helper.reduceEndpointRequest) {\n return helper.reduceEndpointRequest(options);\n }\n\n return Promise.resolve(options.endpointReq);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that can modify an\n * endpoint response before it gets processed.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `reduceEndpointResponse`, it will just return\n * information for the response.\n *\n * @param options The information of the response and the reference to the helper.\n */\n protected _reduceEndpointResponse({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceResponseReducerOptions>): Promise<HTTPResponse> {\n if (helper.reduceEndpointResponse) {\n return helper.reduceEndpointResponse(options);\n }\n\n return Promise.resolve(options.endpointRes);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that can decide if an\n * endpoint response should be streamed or not.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `shouldStreamEndpointResponse`, it will just return\n * `true`.\n *\n * @param options The information of the response and the reference to the helper.\n */\n protected _shouldStreamEndpointResponse({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceResponseReducerOptions>): Promise<boolean> {\n if (helper.shouldStreamEndpointResponse) {\n return helper.shouldStreamEndpointResponse(options);\n }\n\n return Promise.resolve(true);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that handles a\n * response in case it already said that a response shouldn't be streamed.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `shouldStreamEndpointResponse`, it will throw an\n * error.\n *\n * @param options The information of the response and the reference to the helper.\n * @throws If the helper doesn't implement `handleEndpointResponse`.\n */\n protected _handleEndpointResponse({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceResponseReducerOptions>): Promise<void> {\n if (!helper.handleEndpointResponse) {\n throw new Error('You must implement handleEndpointResponse');\n }\n\n return helper.handleEndpointResponse(options);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that handles an error\n * on an endpoint request.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `handleEndpointError`, it will just send the error to\n * the next middleware/error handler.\n *\n * @param options The information of the response and the reference to the helper.\n */\n protected _handleEndpointError({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceErrorHandlerOptions>): void {\n if (helper.handleEndpointError) {\n return helper.handleEndpointError(options);\n }\n\n return options.next(options.error);\n }\n /**\n * Validates and formats the customization options sent to the controller.\n *\n * @param options The options sent to the constructor.\n */\n protected _formatOptions(\n options: GatewayControllerExtraOptions,\n ): GatewayControllerExtraOptions {\n if (options.root) {\n const root = removeSlashes(options.root).trim();\n return { ...options, root };\n }\n\n return options;\n }\n /**\n * Validates a router/HTTP method that the controller intends to use for an endpoint. If\n * it's not valid, it will return `all`.\n *\n * @param method The HTTP method for the endpoint.\n */\n protected _validateHTTPMethod(method: string): RouterMethod {\n const newMethod = method.toLowerCase();\n return [\n 'get',\n 'head',\n 'post',\n 'patch',\n 'put',\n 'delete',\n 'connect',\n 'options',\n 'trace',\n ].includes(newMethod)\n ? (newMethod as RouterMethod)\n : 'all';\n }\n /**\n * Creates the API client configuration based on the controller routes.\n */\n protected _createAPIConfig(): GatewayControllerAPIConfig {\n let endpoints: APIClientOptions['endpoints'];\n const { root } = this._options;\n if (root) {\n endpoints = Object.keys(this._endpoints).reduce<\n Record<string, GatewayConfigEndpointDefinition>\n >((acc, name) => {\n const endpoint = this._endpoints[name]!;\n let newEndpoint;\n if (typeof endpoint === 'string') {\n newEndpoint = removeSlashes(endpoint);\n newEndpoint = `${root}/${newEndpoint}`;\n } else {\n const endpointPath = removeSlashes(endpoint.path);\n newEndpoint = {\n ...endpoint,\n path: `${root}/${endpointPath}`,\n };\n }\n\n acc[name] = newEndpoint;\n return acc;\n }, {});\n } else {\n endpoints = this._endpoints;\n }\n\n return {\n url: `/${this._route}`,\n endpoints: unflat({ target: endpoints }),\n };\n }\n}\n/**\n * A function to generate a list of middlewares that can be executed before the tontroller\n * main middleware.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerGetMiddlewaresFn = (app: Jimpex) => MiddlewareLike[];\n/**\n * The options for the controller creator that mounts the {@link GatewayController}.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerCreatorOptions =\n DeepPartial<GatewayControllerExtraOptions> & {\n /**\n * The name the creator will use to register the controller in the container. No,\n * this is not a typo. The creator will register the controller so other services can\n * access the `getAPIConfig` method. The service will be available after the app\n * routes are mounted.\n * If this is overwritten, the creator will ensure that the name ends with `Gateway`;\n * and if overwritten, but it doesn't include `Gateway` at the end, and no\n * `gatewaySettingName` was defined, the creator will use the custom name (without\n * `Gatway`) for `gatewaySettingName`.\n *\n * @default 'apiGateway'\n */\n serviceName?: string;\n /**\n * The name of the helper service the creator will try to obtain from the container.\n * If `serviceName` is overwritten, the default for this will be\n * `${serviceName}Helper`.\n *\n * @default 'apiGatewayHelper'\n */\n helperServiceName?: string;\n /**\n * The name of the configuration setting where the gateway configuration is stored. If\n * not overwritten, check the description of `serviceName` to understand which will be\n * its default value.\n *\n * @default 'api'\n */\n gatewaySettingName?: string;\n /**\n * The class the creator will instantiate. Similar to the API Client, this allows for\n * extra customization as you can send a custom subclass of the\n * {@link GatewayController}.\n *\n * @default GatewayController\n */\n gatewayClass?: typeof GatewayController;\n /**\n * A function to generate a list of middlewares that can be executed before the\n * controller main middleware.\n */\n getMiddlewares?: GatewayControllerGetMiddlewaresFn;\n };\n/**\n * Creates a controller that allows the application to mount routes that will work like\n * gateway to a specific API.\n *\n * @group Controllers\n * @group Controllers/Gateway\n */\nexport const gatewayController = controllerProviderCreator(\n (options: GatewayControllerCreatorOptions = {}) =>\n (app, route) => {\n /**\n * Formats the name in order to keep consistency with the helper service and the\n * configuration setting: If the `serviceName` is different from the default, make\n * sure it ends with `Gateway`, set the default helper service name to\n * `${serviceName}Helper`, and the default configuration setting to the same as the\n * service name (without the `Gateway`).\n * This way, if you just use `myApi`, the service name will be `myApiGateway`, the\n * helper name will be `myApiGatewayHelper` and the configuration setting `myApi`.\n */\n const defaultServiceName = 'apiGateway';\n let defaultHelperServiceName = 'apiGatewayHelper';\n let defaultConfigSetting = 'api';\n let { serviceName = defaultServiceName } = options;\n if (serviceName !== defaultServiceName) {\n defaultConfigSetting = serviceName;\n if (!serviceName.match(/gateway$/i)) {\n serviceName = `${serviceName}Gateway`;\n }\n defaultHelperServiceName = `${serviceName}Helper`;\n }\n // Register the service.\n app.set(serviceName, () => {\n const {\n helperServiceName = defaultHelperServiceName,\n gatewaySettingName = defaultConfigSetting,\n gatewayClass: GatewayClass = GatewayController,\n } = options;\n\n const gtConfig = app.getConfig<GatewayConfig>(gatewaySettingName);\n\n return new GatewayClass({\n ...options,\n apiConfigSetting: gatewaySettingName,\n gatewayConfig: gtConfig,\n route,\n inject: {\n http: app.get('http'),\n getHelperService: () => app.try(helperServiceName),\n },\n });\n });\n\n return controller(() => {\n // Get the controller.\n const ctrl = app.get<GatewayController>(serviceName);\n /**\n * Check if there are actual middlewares to be included, and in case there are\n * Jimpex middlewares, connect them.\n */\n let useMiddlewares: ExpressMiddleware[] | undefined;\n if (options.getMiddlewares) {\n useMiddlewares = options\n .getMiddlewares(app)\n .map((middleware) => {\n if ('middleware' in middleware) {\n return middleware.connect(app) as ExpressMiddleware | undefined;\n }\n\n return middleware as ExpressMiddleware;\n })\n .filter(notUndefined);\n }\n\n // Add the routes to the router and return it.\n return ctrl.addRoutes(app.get('router'), useMiddlewares);\n });\n },\n);\n"],"mappings":";;;AAAA,SAAS,+BAA+B;AACxC,SAAS,MAAM,cAAc;AAE7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAweA,MAAM,kBAAkB;AAAA;AAAA;AAAA;AAAA,EAiD7B,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACL,GAAwC;AAlDxC;AAAA;AAAA;AAAA,wBAAmB;AAOnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAmB;AAInB;AAAA;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ACtC,6BAAuB;AACvB,UAAI,CAAC,YAAY,MAAM,WAAW,GAAG;AACnC,sBAAc,GAAG,WAAW;AAAA,MAC9B;AACA,iCAA2B,GAAG,WAAW;AAAA,IAC3C;AAEA,QAAI,IAAI,aAAa,MAAM;AACzB,YAAM;AAAA,QACJ,oBAAoB;AAAA,QACpB,qBAAqB;AAAA,QACrB,cAAc,eAAe;AAAA,MAC/B,IAAI;AAEJ,YAAM,WAAW,IAAI,UAAyB,kBAAkB;AAEhE,aAAO,IAAI,aAAa;AAAA,QACtB,GAAG;AAAA,QACH,kBAAkB;AAAA,QAClB,eAAe;AAAA,QACf;AAAA,QACA,QAAQ;AAAA,UACN,MAAM,IAAI,IAAI,MAAM;AAAA,UACpB,kBAAkB,MAAM,IAAI,IAAI,iBAAiB;AAAA,QACnD;AAAA,MACF,CAAC;AAAA,IACH,CAAC;AAED,WAAO,WAAW,MAAM;AAEtB,YAAM,OAAO,IAAI,IAAuB,WAAW;AAKnD,UAAI;AACJ,UAAI,QAAQ,gBAAgB;AAC1B,yBAAiB,QACd,eAAe,GAAG,EAClB,IAAI,CAAC,eAAe;AACnB,cAAI,gBAAgB,YAAY;AAC9B,mBAAO,WAAW,QAAQ,GAAG;AAAA,UAC/B;AAEA,iBAAO;AAAA,QACT,CAAC,EACA,OAAO,YAAY;AAAA,MACxB;AAGA,aAAO,KAAK,UAAU,IAAI,IAAI,QAAQ,GAAG,cAAc;AAAA,IACzD,CAAC;AAAA,EACH;AACJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../../src/controllers/utils/gateway.ts"],"sourcesContent":["import { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport { flat, unflat } from '@homer0/object-utils';\nimport type { APIClientOptions } from '@homer0/api-utils';\nimport {\n controllerProviderCreator,\n controller,\n createRouteExpression,\n removeSlashes,\n notUndefined,\n type MiddlewareLike,\n} from '../../utils';\nimport type { HTTP, HTTPFetchOptions } from '../../services';\nimport type { Jimpex } from '../../app';\nimport {\n RouterMethod,\n DeepPartial,\n Request,\n Response,\n NextFunction,\n HTTPResponse,\n Router,\n ExpressMiddleware,\n AsyncExpressMiddleware,\n} from '../../types';\n/**\n * The extended definition for endpoints.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfigEndpointProps = {\n /**\n * The path to the endpoint relative to the entry point. It can include placeholders for\n * parameters like `/:parameter/`.\n */\n path: string;\n /**\n * The router (HTTP) method for the endpoint.\n *\n * @default 'all'\n */\n method?: RouterMethod;\n};\n/**\n * The definition of an endpoint: it can be just the path, relative to the entry point, or\n * an object in which you can also specify things like the method.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfigEndpointDefinition = string | GatewayConfigEndpointProps;\n/**\n * The dictionary of endpoints the controller uses. The reason for this type is that this\n * could be a flat dictionary, or a nested one.\n *\n * @example\n *\n * <caption>A flat dictionary</caption>\n *\n * {\n * random: '/random',\n * users: '/users',\n * userById: {\n * path: '/users/:id',\n * method: 'get',\n * },\n * }\n *\n * @example\n *\n * <caption>A nested dictionary</caption>\n *\n * {\n * random: '/random',\n * users: {\n * list: '/users',\n * byId: {\n * path: '/users/:id',\n * method: 'get',\n * },\n * },\n * }\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfigEndpoints = {\n [key: string]: GatewayConfigEndpointDefinition | GatewayConfigEndpoints;\n};\n/**\n * The configuration for the gateway the controller uses.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfig = {\n /**\n * The entry point to the API the controller will make the requests to.\n */\n url: string;\n /**\n * The dictionary of enpoints the gateway will make available.\n */\n gateway: GatewayConfigEndpoints;\n};\n/**\n * The options for how the gateway will handle the headers from the requests and the\n * responses.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerHeaderOptions = {\n /**\n * Whether or not to include the header with the request's IP address.\n *\n * @default true\n */\n useXForwardedFor: boolean;\n /**\n * Whether or not to copy all custom headers from the request. By custom header, it\n * means all the headers which names start with `x-`.\n *\n * @default true\n */\n copyCustomHeaders: boolean;\n /**\n * A list of \"known\" headers the gateway will try to copy from the incoming request.\n *\n * @default ['authorization','content-type', 'referer', 'user-agent']\n */\n copy: string[];\n /**\n * A list of \"known\" headers the gateway will try to remove the response.\n *\n * @default ['server', 'x-powered-by']\n */\n remove: string[];\n};\n/**\n * The extra options for the gateway controller. They are \"extra\" because they are mostly\n * helpers for when used with an API client, or for optional features.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerExtraOptions = {\n /**\n * This is really a helper for when the gateway is used with an API client. The idea is\n * that, by default, the routes are mounted on the controller route, but with this\n * option, you can specify another sub path. For example: The controller is mounted on\n * `/routes`, and if you set `root` to `gateway`, all the routes will be on\n * `/routes/gateway`.\n *\n * This become important (and useful) when you get the API client configuration (with\n * `getAPIConfig`): The `url` will be the controller route, but all the endpoints will\n * be modified and prefixed with the `root`, that way, you can have multiple gateways in\n * the same \"base route\".\n *\n * It can also includes placeholders for parameters like `/:parameter/`, that will be\n * replaced with the `placeholders` option when `getAPIConfig` gets called.\n *\n * @default ''\n */\n root: string;\n /**\n * This is another option for when the gateway is used with an API client. When calling\n * `getAPIConfig`, all the endpoints will be wrapped inside an object named after this\n * option. For example: `{ url: '...', endpoints: { api: { ... } } }`.\n *\n * @default 'api'\n */\n apiConfigSetting: string;\n /**\n * The options for how the gateway will handle the headers from the requests and the\n * responses.\n */\n headers: GatewayControllerHeaderOptions;\n};\n/**\n * The required options for the gateway controller.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerOptions = {\n /**\n * The configuration for the API the gateway will make the requests to.\n */\n gatewayConfig: GatewayConfig;\n /**\n * The route where the controller is mounted.\n */\n route: string;\n} & DeepPartial<GatewayControllerExtraOptions>;\n/**\n * The information for a request the controller will make.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerRequest = {\n /**\n * The URL for the request.\n */\n url: string;\n /**\n * The options for the fetch client that will make the requests.\n */\n options: HTTPFetchOptions;\n};\n/**\n * The information for an endpoint the gateway is calling.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerEndpointInfo = {\n /**\n * The name of the endpoint in the configuration.\n */\n name: string;\n /**\n * The properties (path and method) of the endpoint.\n */\n definition: GatewayConfigEndpointDefinition;\n};\n/**\n * These are the base options sent to all the helper service functions.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceBaseFnOptions = {\n /**\n * The information of the endpoint the gateway is calling.\n */\n endpoint: GatewayControllerEndpointInfo;\n /**\n * The request recived by the application.\n */\n req: Request;\n /**\n * The response object created by the application.\n */\n res: Response;\n /**\n * The function to call the next middleware in the chain.\n */\n next: NextFunction;\n};\n/**\n * The information sent to the helper service in order to modify, or not, a request before\n * it is sent.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceRequestReducerOptions =\n GatewayHelperServiceBaseFnOptions & {\n /**\n * The options the controller created for the fetch client.\n */\n endpointReq: GatewayControllerRequest;\n };\n/**\n * A function that can be used to modify the information of an endpoint before making a\n * request.\n *\n * @param options The information of the request.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceRequestReducer = (\n options: GatewayHelperServiceRequestReducerOptions,\n) => Promise<GatewayControllerRequest>;\n/**\n * The information sent to the helper service in order to modify a response before\n * processing it, decide if it should be streamed or not, and even handle it.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceResponseReducerOptions =\n GatewayHelperServiceBaseFnOptions & {\n /**\n * The response from the endpoint request.\n */\n endpointRes: HTTPResponse;\n };\n/**\n * A function that can be used to modify the response of an endpoint before the controller\n * processes it.\n *\n * @param options The information of the response.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceResponseReducer = (\n options: GatewayHelperServiceResponseReducerOptions,\n) => Promise<HTTPResponse>;\n/**\n * A function that can be used to tell the controller to stream the response of an\n * endpoint or not.\n * If it returns `false`, the function to handle responses should be defined, otherwise,\n * an error will be generated.\n *\n * @param options The information of the response.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceStreamVerification = (\n options: GatewayHelperServiceResponseReducerOptions,\n) => Promise<boolean>;\n/**\n * A function to handle the response of an endpoint. This is called when the helper\n * service tells the controller that the endpoint shouldn't be streamed, so this method\n * should handle the response.\n *\n * @param options The information of the response.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceResponseHandler = (\n options: GatewayHelperServiceResponseReducerOptions,\n) => Promise<void>;\n/**\n * The information sent to the helper service in order to handle a failed request for an\n * endpoint.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceErrorHandlerOptions =\n GatewayHelperServiceBaseFnOptions & {\n /**\n * The error generated during the request.\n */\n error: Error;\n };\n/**\n * A function to handle the error of an endpoint request.\n *\n * @param options The information of the error.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceErrorHandler = (\n options: GatewayHelperServiceErrorHandlerOptions,\n) => void;\n/**\n * The interface of a helper service that can intercept/modify the requests and responses\n * the gateway makes.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperService = Partial<{\n /**\n * A function that is called before an endpoint request is made.\n */\n reduceEndpointRequest: GatewayHelperServiceRequestReducer;\n /**\n * A function that is called with the response of an endpoint request.\n */\n reduceEndpointResponse: GatewayHelperServiceResponseReducer;\n /**\n * A function called in order to validate if an endpoint response should be streamed or\n * not. If the function returns `false`, `handleEndpointResponse` will be called.\n */\n shouldStreamEndpointResponse: GatewayHelperServiceStreamVerification;\n /**\n * A function called when `shouldStreamEndpointResponse` returns `false`. The function\n * should handle the response for the application.\n */\n handleEndpointResponse: GatewayHelperServiceResponseHandler;\n /**\n * A function called when an error is generated during an endpoint request/processing.\n */\n handleEndpointError: GatewayHelperServiceErrorHandler;\n}>;\n/**\n * Utility type for the options object sent to the \"proxy methods\" the controller has for\n * the helper service.\n *\n * @template T The type of the options for a specific helper service function.\n * @access protected\n * @group Controllers/Gateway\n */\nexport type GatewayControllerHelperOptions<T> = T & {\n /**\n * The reference for the helper service.\n */\n helper: GatewayHelperService;\n};\n/**\n * The information for a single HTTP method an endpoint can handle.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerRouteMethod = {\n /**\n * The method for the route.\n */\n method: RouterMethod;\n /**\n * The information of the endpoint.\n */\n endpoint: GatewayControllerEndpointInfo;\n};\n/**\n * The information for all the HTTP methods that can be handled for an endpoint.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerRoute = {\n /**\n * The path to the endpoint, relative to the entry point.\n */\n path: string;\n /**\n * The path for the route in the controller. This is different from `path` as it's possible for\n * the gateway to be implemented using the `root` option.\n */\n route: string;\n /**\n * A list with all the methods the controller uses on the route.\n */\n methods: GatewayControllerRouteMethod[];\n};\n/**\n * The API client configuration the gateway can generate for its endpoints.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerAPIConfig = {\n /**\n * The base URL for the API.\n */\n url: string;\n /**\n * The dictionary of endpoints the controller handles.\n */\n endpoints: APIClientOptions['endpoints'];\n};\n/**\n * The options sent to {@link GatewayController.getAPIConfig}.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerAPIConfigOptions = {\n /**\n * This can be used to overwrite the gateway's `apiConfigSetting` option, and set a new\n * setting as a wrapper for the endpoints.\n */\n setting?: string;\n /**\n * A dictionary of values for possible placeholders that were sent using the `root`\n * option.\n */\n placeholders?: Record<string, string>;\n};\n/**\n * The options to construct a {@link GatewayController}.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerConstructorOptions = GatewayControllerOptions & {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n http: HTTP;\n /**\n * A function to get a possible helper service. This is injected as a \"getter\" to not\n * interrupt the DIC \"lifecycle\": controllers are initialized right when the app\n * starts, and injecting a reference would force the service to be initialized too,\n * even if a request is not being made.\n */\n getHelperService?: () => GatewayHelperService | undefined;\n };\n};\n/**\n * The options for {@link GatewayController._addRoute}.\n *\n * @access protected\n * @group Controllers/Gateway\n */\nexport type AddGatewayRouteOptions = {\n /**\n * The reference for the router in which the middlewares will be added.\n */\n router: Router;\n /**\n * The router method in which the middlewares will be added.\n */\n method: RouterMethod;\n /**\n * The route in which the middlewares will be added.\n */\n route: string;\n /**\n * The middleware created by {@link GatewayController}, that makes the request.\n */\n gatewayMiddleware: AsyncExpressMiddleware;\n /**\n * A list of extra middlewares to prepend to the gateway middleware.\n */\n middlewares: ExpressMiddleware[];\n};\n/**\n * A utility controller that generates routes that act as a gateway for a specific API.\n *\n * @group Controller Classes\n * @group Controllers/Gateway\n * @prettierignore\n */\nexport class GatewayController {\n /**\n * The service that makes HTTP requests.\n */\n protected readonly http: HTTP;\n /**\n * A function to get a possible helper service. This is injected as a \"getter\" to not\n * interrupt the DIC \"lifecycle\": controllers are initialized right when the app\n * starts, and injecting a reference would force the service to be initialized too,\n * even if a request is not being made.\n */\n protected readonly _getHelperService: () => GatewayHelperService | undefined;\n /**\n * The information, url and endpoints, for the gateway the controller will make requests to.\n */\n protected readonly _gatewayConfig: GatewayConfig;\n /**\n * The route in which the controller is mounted.\n */\n protected readonly _route: string;\n /**\n * A regular expression that will be used to remove the controller route from a\n * request path. This will allow the main middleware to extract the path to where the\n * request should be made.\n */\n protected readonly _routeExpression: RegExp;\n /**\n * The controller customization options.\n */\n protected readonly _options: GatewayControllerExtraOptions;\n /**\n * A flat dictionary with the endpoints information.\n */\n protected readonly _endpoints: Record<string, GatewayConfigEndpointDefinition>;\n /**\n * The entry URL for the API client configuration the controller can generate.\n */\n protected readonly _apiConfigUrl: string;\n /**\n * The generated endpoints for the API client configuration the controller can generate.\n */\n protected readonly _apiConfigEndpoints: APIClientOptions['endpoints'];\n /**\n * The list of routes the controller can handle.\n */\n protected readonly _routes: GatewayControllerRoute[];\n /**\n * @param options The options to construct the controller.\n */\n constructor({\n inject,\n route,\n gatewayConfig,\n ...options\n }: GatewayControllerConstructorOptions) {\n this.http = inject.http;\n this._getHelperService = inject.getHelperService || (() => undefined);\n this._route = removeSlashes(route);\n this._options = this._formatOptions(\n deepAssignWithOverwrite(\n {\n root: '',\n apiConfigSetting: 'api',\n headers: {\n useXForwardedFor: true,\n copyCustomHeaders: true,\n copy: ['authorization', 'content-type', 'referer', 'user-agent'],\n remove: ['server', 'x-powered-by', 'content-encoding'],\n },\n },\n options,\n ),\n );\n this._gatewayConfig = {\n ...gatewayConfig,\n url: removeSlashes(gatewayConfig.url, false, true),\n };\n this._routeExpression = createRouteExpression(\n this._options.root ? `${this._route}/${this._options.root}` : this._route,\n true,\n true,\n );\n this._endpoints = this._formatEndpoints();\n this._routes = this._createRoutes();\n const { url, endpoints } = this._createAPIConfig();\n this._apiConfigUrl = url;\n this._apiConfigEndpoints = endpoints;\n }\n /**\n * Generates an API client configuration based on the controller routes.\n *\n * @param options The options to customize the generated configuration.\n */\n getAPIConfig({\n setting,\n placeholders = {},\n }: GatewayControllerAPIConfigOptions = {}): Readonly<GatewayControllerAPIConfig> {\n const useSetting = setting || this._options.apiConfigSetting;\n let url: string;\n const placeholdersEntries = Object.entries(placeholders);\n if (placeholdersEntries.length) {\n url = placeholdersEntries.reduce<string>(\n (acc, [key, value]) => acc.replace(`:${key}`, value),\n this._apiConfigUrl,\n );\n } else {\n url = this._apiConfigUrl;\n }\n\n return {\n url,\n endpoints: {\n [useSetting]: this._apiConfigEndpoints,\n },\n };\n }\n /**\n * Mounts the middlewares in the router in order to make the requests.\n *\n * @param router A reference to the application router.\n * @param middlewares A list of extra middlewares to execute before the gateway\n * middleware.\n */\n addRoutes(router: Router, middlewares: ExpressMiddleware[] = []): Router {\n this._routes.forEach((route) => {\n route.methods.forEach((info) => {\n this._addRoute({\n router,\n method: info.method,\n route: route.route,\n gatewayMiddleware: this._createGatewayMiddleware(info.endpoint),\n middlewares,\n });\n });\n });\n\n return router;\n }\n /**\n * The customization options.\n */\n get options(): Readonly<GatewayControllerExtraOptions> {\n return { ...this._options };\n }\n /**\n * The configuration for the gateway the controller will make requests to.\n */\n get gatewayConfig(): Readonly<GatewayConfig> {\n return { ...this._gatewayConfig };\n }\n /**\n * Generates a middleware that will make the request to an endpoint and stream the\n * response.\n *\n * @param endpoint The information of the endpoint the middleware will handle.\n */\n protected _createGatewayMiddleware(\n endpoint: GatewayControllerEndpointInfo,\n ): AsyncExpressMiddleware {\n return async (req, res, next) => {\n const {\n _options: { headers: headersOptions },\n _gatewayConfig: { url: gatewayUrl },\n _routeExpression: routeExpression,\n } = this;\n // Remove the controller route from the requested URL.\n const reqPath = req.originalUrl.replace(routeExpression, '');\n // Process the headers for the request.\n let headers: Record<string, string> = {};\n // - Copy the headers from the incoming request.\n headersOptions.copy.forEach((name) => {\n if (req.headers[name]) {\n headers[name] = req.headers[name] as string;\n }\n });\n // - Copy the custom headers.\n if (headersOptions.copyCustomHeaders) {\n headers = deepAssignWithOverwrite<Record<string, string>>(\n headers,\n this.http.getCustomHeadersFromRequest(req),\n );\n }\n // - Include the IP on the X-Forwarded-For header, if enabled.\n if (headersOptions.useXForwardedFor) {\n const ip = this.http.getIPFromRequest(req);\n if (ip) {\n headers['x-forwarded-for'] = ip;\n }\n }\n\n const method = req.method.toUpperCase();\n // If the request has a body and the method is not `GET`, stringify it.\n let body: string | undefined;\n if (method !== 'GET' && typeof req.body === 'object') {\n body = JSON.stringify(req.body);\n // If there's no `content-type`, let's assume it's JSON.\n if (!headers['content-type']) {\n headers['content-type'] = 'application/json';\n }\n }\n\n /**\n * Get the helper service, if there's one, and define the base options for its\n * methods.\n */\n const helper = this._getHelperService() || {};\n const helperBasePayload = {\n endpoint,\n req,\n res,\n next,\n helper,\n };\n\n try {\n // Reduce the request information before using it.\n const request = await this._reduceEndpointRequest({\n endpointReq: {\n url: `${gatewayUrl}/${reqPath}`,\n options: {\n method,\n headers,\n body,\n },\n },\n ...helperBasePayload,\n });\n // Make the actual request.\n const responseRaw = await this.http.fetch(request.url, request.options);\n // Reduce the response information before using it.\n const response = await this._reduceEndpointResponse({\n endpointRes: responseRaw,\n ...helperBasePayload,\n });\n // Validate if the response should be streamed.\n const shouldStream = await this._shouldStreamEndpointResponse({\n endpointRes: responseRaw,\n ...helperBasePayload,\n });\n\n if (shouldStream) {\n if (response.body === null) {\n throw new Error('The response body is null');\n }\n\n /**\n * If the response should be streamed, set the status, remove unwanted headers,\n * and pipe it to the application response object.\n */\n res.status(response.status);\n response.headers.forEach((value, name) => {\n if (!headersOptions.remove.includes(name)) {\n res.setHeader(name, value);\n }\n });\n\n response.body.pipe(res).on('error', (error) => {\n next(error);\n });\n } else {\n /**\n * If the response should not be streamed, send it to the helper method to\n * handle it.\n */\n await this._handleEndpointResponse({\n endpointRes: response,\n ...helperBasePayload,\n });\n }\n } catch (error) {\n // Something failed, so let's pass the error to the helper service.\n this._handleEndpointError({\n error: error as Error,\n ...helperBasePayload,\n });\n }\n };\n }\n /**\n * Mounts the middleware(s) for an endpoint in the router.\n *\n * @param options The information of the endpoint and how it needs to be added.\n */\n protected _addRoute({\n router,\n method,\n route,\n gatewayMiddleware,\n middlewares,\n }: AddGatewayRouteOptions): void {\n router[method](route, [...middlewares, gatewayMiddleware]);\n }\n /**\n * Formats the endpoints for the gateway into a flat dictionary without nesting.\n */\n protected _formatEndpoints(): Record<string, GatewayConfigEndpointDefinition> {\n return flat({\n target: this._gatewayConfig.gateway,\n shouldFlatten: (_, value) => {\n const useValue = value as { path?: string };\n return typeof useValue.path === 'undefined';\n },\n });\n }\n /**\n * Based on the information from the endpoints, this method will create the routes the\n * controller will later add on a router.\n *\n * @throws If there's more than one endpoint using the same path with the same HTTP\n * method.\n */\n protected _createRoutes(): GatewayControllerRoute[] {\n const routes: Record<\n string,\n {\n path: string;\n methods: Partial<Record<RouterMethod, string>>;\n }\n > = {};\n Object.keys(this._endpoints).forEach((name) => {\n const endpoint = this._endpoints[name]!;\n let endpointPath: string;\n let endpointMethod: RouterMethod;\n if (typeof endpoint === 'string') {\n endpointPath = endpoint;\n endpointMethod = 'all';\n } else {\n endpointPath = endpoint.path;\n endpointMethod = endpoint.method\n ? this._validateHTTPMethod(endpoint.method)\n : 'all';\n }\n\n endpointPath = removeSlashes(endpointPath);\n if (!routes[endpointPath]) {\n routes[endpointPath] = {\n path: endpointPath,\n methods: {},\n };\n }\n\n if (routes[endpointPath]!.methods[endpointMethod]) {\n const repeatedEndpoint = routes[endpointPath]!.methods[endpointMethod];\n throw new Error(\n \"You can't have two gateway endpoints to the same path and with the same \" +\n `HTTP method: '${repeatedEndpoint}' and '${name}'`,\n );\n }\n\n routes[endpointPath]!.methods[endpointMethod] = name;\n });\n\n const routePrefixes = this._options.root ? `/${this._options.root}/` : '/';\n return Object.keys(routes).map((endpointPath) => {\n const info = routes[endpointPath]!;\n return {\n path: info.path,\n route: `${routePrefixes}${info.path}`,\n methods: Object.keys(info.methods).map((methodNameRaw) => {\n const methodName = methodNameRaw as RouterMethod;\n const endpointName = info.methods[methodName]!;\n const endpointDefinition = this._endpoints[endpointName]!;\n return {\n method: methodName,\n endpoint: {\n name: endpointName,\n definition: endpointDefinition,\n },\n };\n }),\n };\n });\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that can modify an\n * endpoint request before it gets made.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `reduceEndpointRequest`, it will just return\n * information for the request.\n *\n * @param options The information of the request and the reference to the helper.\n */\n protected _reduceEndpointRequest({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceRequestReducerOptions>): Promise<GatewayControllerRequest> {\n if (helper.reduceEndpointRequest) {\n return helper.reduceEndpointRequest(options);\n }\n\n return Promise.resolve(options.endpointReq);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that can modify an\n * endpoint response before it gets processed.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `reduceEndpointResponse`, it will just return\n * information for the response.\n *\n * @param options The information of the response and the reference to the helper.\n */\n protected _reduceEndpointResponse({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceResponseReducerOptions>): Promise<HTTPResponse> {\n if (helper.reduceEndpointResponse) {\n return helper.reduceEndpointResponse(options);\n }\n\n return Promise.resolve(options.endpointRes);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that can decide if an\n * endpoint response should be streamed or not.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `shouldStreamEndpointResponse`, it will just return\n * `true`.\n *\n * @param options The information of the response and the reference to the helper.\n */\n protected _shouldStreamEndpointResponse({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceResponseReducerOptions>): Promise<boolean> {\n if (helper.shouldStreamEndpointResponse) {\n return helper.shouldStreamEndpointResponse(options);\n }\n\n return Promise.resolve(true);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that handles a\n * response in case it already said that a response shouldn't be streamed.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `shouldStreamEndpointResponse`, it will throw an\n * error.\n *\n * @param options The information of the response and the reference to the helper.\n * @throws If the helper doesn't implement `handleEndpointResponse`.\n */\n protected _handleEndpointResponse({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceResponseReducerOptions>): Promise<void> {\n if (!helper.handleEndpointResponse) {\n throw new Error('You must implement handleEndpointResponse');\n }\n\n return helper.handleEndpointResponse(options);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that handles an error\n * on an endpoint request.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `handleEndpointError`, it will just send the error to\n * the next middleware/error handler.\n *\n * @param options The information of the response and the reference to the helper.\n */\n protected _handleEndpointError({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceErrorHandlerOptions>): void {\n if (helper.handleEndpointError) {\n return helper.handleEndpointError(options);\n }\n\n return options.next(options.error);\n }\n /**\n * Validates and formats the customization options sent to the controller.\n *\n * @param options The options sent to the constructor.\n */\n protected _formatOptions(\n options: GatewayControllerExtraOptions,\n ): GatewayControllerExtraOptions {\n if (options.root) {\n const root = removeSlashes(options.root).trim();\n return { ...options, root };\n }\n\n return options;\n }\n /**\n * Validates a router/HTTP method that the controller intends to use for an endpoint. If\n * it's not valid, it will return `all`.\n *\n * @param method The HTTP method for the endpoint.\n */\n protected _validateHTTPMethod(method: string): RouterMethod {\n const newMethod = method.toLowerCase();\n return [\n 'get',\n 'head',\n 'post',\n 'patch',\n 'put',\n 'delete',\n 'connect',\n 'options',\n 'trace',\n ].includes(newMethod)\n ? (newMethod as RouterMethod)\n : 'all';\n }\n /**\n * Creates the API client configuration based on the controller routes.\n */\n protected _createAPIConfig(): GatewayControllerAPIConfig {\n let endpoints: APIClientOptions['endpoints'];\n const { root } = this._options;\n if (root) {\n endpoints = Object.keys(this._endpoints).reduce<\n Record<string, GatewayConfigEndpointDefinition>\n >((acc, name) => {\n const endpoint = this._endpoints[name]!;\n let newEndpoint;\n if (typeof endpoint === 'string') {\n newEndpoint = removeSlashes(endpoint);\n newEndpoint = `${root}/${newEndpoint}`;\n } else {\n const endpointPath = removeSlashes(endpoint.path);\n newEndpoint = {\n ...endpoint,\n path: `${root}/${endpointPath}`,\n };\n }\n\n acc[name] = newEndpoint;\n return acc;\n }, {});\n } else {\n endpoints = this._endpoints;\n }\n\n return {\n url: `/${this._route}`,\n endpoints: unflat({ target: endpoints }),\n };\n }\n}\n/**\n * A function to generate a list of middlewares that can be executed before the tontroller\n * main middleware.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerGetMiddlewaresFn = (app: Jimpex) => MiddlewareLike[];\n/**\n * The options for the controller creator that mounts the {@link GatewayController}.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerCreatorOptions =\n DeepPartial<GatewayControllerExtraOptions> & {\n /**\n * The name the creator will use to register the controller in the container. No,\n * this is not a typo. The creator will register the controller so other services can\n * access the `getAPIConfig` method. The service will be available after the app\n * routes are mounted.\n * If this is overwritten, the creator will ensure that the name ends with `Gateway`;\n * and if overwritten, but it doesn't include `Gateway` at the end, and no\n * `gatewaySettingName` was defined, the creator will use the custom name (without\n * `Gatway`) for `gatewaySettingName`.\n *\n * @default 'apiGateway'\n */\n serviceName?: string;\n /**\n * The name of the helper service the creator will try to obtain from the container.\n * If `serviceName` is overwritten, the default for this will be\n * `${serviceName}Helper`.\n *\n * @default 'apiGatewayHelper'\n */\n helperServiceName?: string;\n /**\n * The name of the configuration setting where the gateway configuration is stored. If\n * not overwritten, check the description of `serviceName` to understand which will be\n * its default value.\n *\n * @default 'api'\n */\n gatewaySettingName?: string;\n /**\n * The class the creator will instantiate. Similar to the API Client, this allows for\n * extra customization as you can send a custom subclass of the\n * {@link GatewayController}.\n *\n * @default GatewayController\n */\n gatewayClass?: typeof GatewayController;\n /**\n * A function to generate a list of middlewares that can be executed before the\n * controller main middleware.\n */\n getMiddlewares?: GatewayControllerGetMiddlewaresFn;\n };\n/**\n * Creates a controller that allows the application to mount routes that will work like\n * gateway to a specific API.\n *\n * @group Controllers\n * @group Controllers/Gateway\n */\nexport const gatewayController = controllerProviderCreator(\n (options: GatewayControllerCreatorOptions = {}) =>\n (app, route) => {\n /**\n * Formats the name in order to keep consistency with the helper service and the\n * configuration setting: If the `serviceName` is different from the default, make\n * sure it ends with `Gateway`, set the default helper service name to\n * `${serviceName}Helper`, and the default configuration setting to the same as the\n * service name (without the `Gateway`).\n * This way, if you just use `myApi`, the service name will be `myApiGateway`, the\n * helper name will be `myApiGatewayHelper` and the configuration setting `myApi`.\n */\n const defaultServiceName = 'apiGateway';\n let defaultHelperServiceName = 'apiGatewayHelper';\n let defaultConfigSetting = 'api';\n let { serviceName = defaultServiceName } = options;\n if (serviceName !== defaultServiceName) {\n defaultConfigSetting = serviceName;\n if (!serviceName.match(/gateway$/i)) {\n serviceName = `${serviceName}Gateway`;\n }\n defaultHelperServiceName = `${serviceName}Helper`;\n }\n // Register the service.\n app.set(serviceName, () => {\n const {\n helperServiceName = defaultHelperServiceName,\n gatewaySettingName = defaultConfigSetting,\n gatewayClass: GatewayClass = GatewayController,\n } = options;\n\n const gtConfig = app.getConfig<GatewayConfig>(gatewaySettingName);\n\n return new GatewayClass({\n ...options,\n apiConfigSetting: gatewaySettingName,\n gatewayConfig: gtConfig,\n route,\n inject: {\n http: app.get('http'),\n getHelperService: () => app.try(helperServiceName),\n },\n });\n });\n\n return controller(() => {\n // Get the controller.\n const ctrl = app.get<GatewayController>(serviceName);\n /**\n * Check if there are actual middlewares to be included, and in case there are\n * Jimpex middlewares, connect them.\n */\n let useMiddlewares: ExpressMiddleware[] | undefined;\n if (options.getMiddlewares) {\n useMiddlewares = options\n .getMiddlewares(app)\n .map((middleware) => {\n if ('middleware' in middleware) {\n return middleware.connect(app) as ExpressMiddleware | undefined;\n }\n\n return middleware as ExpressMiddleware;\n })\n .filter(notUndefined);\n }\n\n // Add the routes to the router and return it.\n return ctrl.addRoutes(app.get('router'), useMiddlewares);\n });\n },\n);\n"],"mappings":";;;AAAA,SAAS,+BAA+B;AACxC,SAAS,MAAM,cAAc;AAE7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAweA,MAAM,kBAAkB;AAAA;AAAA;AAAA;AAAA,EAiD7B,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACL,GAAwC;AAlDxC;AAAA;AAAA;AAAA,wBAAmB;AAOnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAmB;AAInB;AAAA;AAAA;AAAA,wBAAmB;AAInB;AAAA;AAAA;AAAA,wBAAmB;AAMnB;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAmB;AAInB;AAAA;AAAA;AAAA,wBAAmB;AAInB;AAAA;AAAA;AAAA,wBAAmB;AAInB;AAAA;AAAA;AAAA,wBAAmB;AAInB;AAAA;AAAA;AAAA,wBAAmB;AAInB;AAAA;AAAA;AAAA,wBAAmB;AAUjB,SAAK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AAA,QACpB,qBAAqB;AAAA,QACrB,cAAc,eAAe;AAAA,MAC/B,IAAI;AAEJ,YAAM,WAAW,IAAI,UAAyB,kBAAkB;AAEhE,aAAO,IAAI,aAAa;AAAA,QACtB,GAAG;AAAA,QACH,kBAAkB;AAAA,QAClB,eAAe;AAAA,QACf;AAAA,QACA,QAAQ;AAAA,UACN,MAAM,IAAI,IAAI,MAAM;AAAA,UACpB,kBAAkB,MAAM,IAAI,IAAI,iBAAiB;AAAA,QACnD;AAAA,MACF,CAAC;AAAA,IACH,CAAC;AAED,WAAO,WAAW,MAAM;AAEtB,YAAM,OAAO,IAAI,IAAuB,WAAW;AAKnD,UAAI;AACJ,UAAI,QAAQ,gBAAgB;AAC1B,yBAAiB,QACd,eAAe,GAAG,EAClB,IAAI,CAAC,eAAe;AACnB,cAAI,gBAAgB,YAAY;AAC9B,mBAAO,WAAW,QAAQ,GAAG;AAAA,UAC/B;AAEA,iBAAO;AAAA,QACT,CAAC,EACA,OAAO,YAAY;AAAA,MACxB;AAGA,aAAO,KAAK,UAAU,IAAI,IAAI,QAAQ,GAAG,cAAc;AAAA,IACzD,CAAC;AAAA,EACH;AACJ;","names":[]}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
__publicField
|
|
3
|
-
} from "../../chunk-
|
|
4
|
-
import fetch from "node-fetch";
|
|
3
|
+
} from "../../chunk-F3FYYIAV.js";
|
|
5
4
|
import urijs from "urijs";
|
|
6
5
|
import { deepAssignWithOverwrite } from "@homer0/deep-assign";
|
|
7
6
|
import { provider } from "../../utils";
|
|
@@ -9,16 +8,22 @@ class HTTP {
|
|
|
9
8
|
/**
|
|
10
9
|
* @param options The options to construct the class.
|
|
11
10
|
*/
|
|
12
|
-
constructor({ inject: { logger }, ...options }) {
|
|
11
|
+
constructor({ inject: { logger, nodeFetch }, ...options }) {
|
|
13
12
|
/**
|
|
14
13
|
* The service used to log information in the terminal.
|
|
15
14
|
*/
|
|
16
15
|
__publicField(this, "_logger");
|
|
16
|
+
/**
|
|
17
|
+
* The node-fetch library. Since it's an ESM only module, Jimpex loads it on boot and makes
|
|
18
|
+
* it available on the container.
|
|
19
|
+
*/
|
|
20
|
+
__publicField(this, "_nodeFetch");
|
|
17
21
|
/**
|
|
18
22
|
* The service customization options.
|
|
19
23
|
*/
|
|
20
24
|
__publicField(this, "_options");
|
|
21
25
|
this._logger = logger;
|
|
26
|
+
this._nodeFetch = nodeFetch;
|
|
22
27
|
this._options = deepAssignWithOverwrite(
|
|
23
28
|
{
|
|
24
29
|
logRequests: false
|
|
@@ -61,7 +66,7 @@ class HTTP {
|
|
|
61
66
|
if (logRequests) {
|
|
62
67
|
this._logRequest(useURL, fetchOptions);
|
|
63
68
|
}
|
|
64
|
-
const response = await
|
|
69
|
+
const response = await this._nodeFetch(useURL, fetchOptions);
|
|
65
70
|
if (logRequests) {
|
|
66
71
|
this._logResponse(response);
|
|
67
72
|
}
|
|
@@ -161,7 +166,8 @@ const httpProvider = provider((app) => {
|
|
|
161
166
|
const logRequests = config.get("debug.logRequests") === true;
|
|
162
167
|
return new HTTP({
|
|
163
168
|
inject: {
|
|
164
|
-
logger: app.get("logger")
|
|
169
|
+
logger: app.get("logger"),
|
|
170
|
+
nodeFetch: app.get("node-fetch")
|
|
165
171
|
},
|
|
166
172
|
logRequests
|
|
167
173
|
});
|