jimpex 8.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 +33 -0
- package/README.md +2 -2
- package/dist/app/index.d.mts +14 -0
- package/dist/app/index.d.ts +5 -4
- package/dist/app/index.js +4 -0
- package/dist/app/jimpex.d.mts +14 -0
- package/dist/app/jimpex.d.ts +3 -2
- package/dist/app/jimpex.js +238 -2
- package/dist/app/jimpex.js.map +1 -1
- package/dist/controllers/common/config.d.mts +79 -0
- package/dist/controllers/common/config.d.ts +4 -3
- package/dist/controllers/common/config.js +18 -0
- package/dist/controllers/common/config.js.map +1 -1
- package/dist/controllers/common/health.d.mts +83 -0
- package/dist/controllers/common/health.d.ts +5 -4
- package/dist/controllers/common/health.js +18 -0
- package/dist/controllers/common/health.js.map +1 -1
- package/dist/controllers/common/index.d.mts +22 -0
- package/dist/controllers/common/index.d.ts +5 -4
- package/dist/controllers/common/index.js +6 -0
- package/dist/controllers/common/statics.d.mts +223 -0
- package/dist/controllers/common/statics.d.ts +13 -5
- package/dist/controllers/common/statics.js +60 -3
- package/dist/controllers/common/statics.js.map +1 -1
- package/dist/controllers/index.d.mts +25 -0
- package/dist/controllers/index.d.ts +5 -4
- package/dist/controllers/index.js +5 -0
- package/dist/controllers/utils/gateway.d.mts +725 -0
- package/dist/controllers/utils/gateway.d.ts +5 -4
- package/dist/controllers/utils/gateway.js +155 -0
- package/dist/controllers/utils/gateway.js.map +1 -1
- package/dist/controllers/utils/index.d.mts +17 -0
- package/dist/controllers/utils/index.d.ts +4 -3
- package/dist/controllers/utils/index.js +4 -0
- package/dist/esm/app/jimpex.js +235 -3
- package/dist/esm/app/jimpex.js.map +1 -1
- package/dist/esm/{chunk-T2T6Q22Z.js → chunk-F3FYYIAV.js} +1 -1
- package/dist/esm/controllers/common/config.js +19 -1
- package/dist/esm/controllers/common/config.js.map +1 -1
- package/dist/esm/controllers/common/health.js +19 -1
- package/dist/esm/controllers/common/health.js.map +1 -1
- package/dist/esm/controllers/common/statics.js +57 -4
- package/dist/esm/controllers/common/statics.js.map +1 -1
- package/dist/esm/controllers/utils/gateway.js +156 -1
- package/dist/esm/controllers/utils/gateway.js.map +1 -1
- package/dist/esm/middlewares/common/errorHandler.js +25 -1
- package/dist/esm/middlewares/common/errorHandler.js.map +1 -1
- package/dist/esm/middlewares/common/forceHTTPS.js +13 -1
- package/dist/esm/middlewares/common/forceHTTPS.js.map +1 -1
- package/dist/esm/middlewares/common/hsts.js +22 -1
- package/dist/esm/middlewares/common/hsts.js.map +1 -1
- package/dist/esm/middlewares/html/fastHTML.js +55 -1
- package/dist/esm/middlewares/html/fastHTML.js.map +1 -1
- package/dist/esm/middlewares/html/showHTML.js +33 -1
- package/dist/esm/middlewares/html/showHTML.js.map +1 -1
- package/dist/esm/middlewares/utils/versionValidator.js +35 -1
- package/dist/esm/middlewares/utils/versionValidator.js.map +1 -1
- package/dist/esm/services/common/appError.js +48 -2
- package/dist/esm/services/common/appError.js.map +1 -1
- package/dist/esm/services/common/httpError.js +10 -1
- package/dist/esm/services/common/httpError.js.map +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 +29 -1
- package/dist/esm/services/frontend/frontendFs.js.map +1 -1
- package/dist/esm/services/frontend/index.js +1 -1
- package/dist/esm/services/html/htmlGenerator.js +51 -1
- package/dist/esm/services/html/htmlGenerator.js.map +1 -1
- package/dist/esm/services/html/index.js +1 -1
- package/dist/esm/services/http/apiClient.js +27 -1
- package/dist/esm/services/http/apiClient.js.map +1 -1
- package/dist/esm/services/http/http.js +60 -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 +49 -2
- package/dist/esm/services/http/responsesBuilder.js.map +1 -1
- package/dist/esm/services/utils/ensureBearerToken.js +17 -1
- package/dist/esm/services/utils/ensureBearerToken.js.map +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/routes.js.map +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-Bwf7JHu9.d.mts +1287 -0
- package/dist/{jimpex-7eaee271.d.ts → index-C6I3NCC-.d.ts} +15 -6
- package/dist/index.d.mts +47 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +9 -0
- package/dist/middlewares/common/errorHandler.d.mts +132 -0
- package/dist/middlewares/common/errorHandler.d.ts +5 -4
- package/dist/middlewares/common/errorHandler.js +24 -0
- package/dist/middlewares/common/errorHandler.js.map +1 -1
- package/dist/middlewares/common/forceHTTPS.d.mts +69 -0
- package/dist/middlewares/common/forceHTTPS.d.ts +6 -5
- package/dist/middlewares/common/forceHTTPS.js +12 -0
- package/dist/middlewares/common/forceHTTPS.js.map +1 -1
- package/dist/middlewares/common/hsts.d.mts +110 -0
- package/dist/middlewares/common/hsts.d.ts +6 -5
- package/dist/middlewares/common/hsts.js +21 -0
- package/dist/middlewares/common/hsts.js.map +1 -1
- package/dist/middlewares/common/index.d.mts +22 -0
- package/dist/middlewares/common/index.d.ts +4 -3
- package/dist/middlewares/common/index.js +6 -0
- package/dist/middlewares/html/fastHTML.d.mts +180 -0
- package/dist/middlewares/html/fastHTML.d.ts +5 -5
- package/dist/middlewares/html/fastHTML.js +54 -0
- package/dist/middlewares/html/fastHTML.js.map +1 -1
- package/dist/middlewares/html/index.d.mts +21 -0
- package/dist/middlewares/html/index.d.ts +4 -4
- package/dist/middlewares/html/index.js +5 -0
- package/dist/middlewares/html/showHTML.d.mts +127 -0
- package/dist/middlewares/html/showHTML.d.ts +5 -5
- package/dist/middlewares/html/showHTML.js +32 -0
- package/dist/middlewares/html/showHTML.js.map +1 -1
- package/dist/middlewares/index.d.mts +30 -0
- package/dist/middlewares/index.d.ts +4 -4
- package/dist/middlewares/index.js +6 -0
- package/dist/middlewares/utils/index.d.mts +20 -0
- package/dist/middlewares/utils/index.d.ts +4 -3
- package/dist/middlewares/utils/index.js +4 -0
- package/dist/middlewares/utils/versionValidator.d.mts +215 -0
- package/dist/middlewares/utils/versionValidator.d.ts +5 -4
- package/dist/middlewares/utils/versionValidator.js +34 -0
- package/dist/middlewares/utils/versionValidator.js.map +1 -1
- package/dist/services/common/appError.d.mts +139 -0
- package/dist/services/common/appError.d.ts +5 -4
- package/dist/services/common/appError.js +47 -1
- package/dist/services/common/appError.js.map +1 -1
- package/dist/services/common/httpError.d.mts +80 -0
- package/dist/services/common/httpError.d.ts +5 -4
- package/dist/services/common/httpError.js +9 -0
- package/dist/services/common/httpError.js.map +1 -1
- package/dist/services/common/index.d.mts +47 -0
- package/dist/services/common/index.d.ts +4 -4
- package/dist/services/common/index.js +4 -1
- package/dist/services/common/sendFile.d.mts +102 -0
- package/dist/services/common/sendFile.d.ts +4 -4
- package/dist/services/frontend/frontendFs.d.mts +96 -0
- package/dist/services/frontend/frontendFs.d.ts +4 -4
- package/dist/services/frontend/frontendFs.js +32 -0
- package/dist/services/frontend/frontendFs.js.map +1 -1
- package/dist/services/frontend/index.d.mts +40 -0
- package/dist/services/frontend/index.d.ts +4 -4
- package/dist/services/frontend/index.js +2 -1
- package/dist/services/html/htmlGenerator.d.mts +237 -0
- package/dist/services/html/htmlGenerator.d.ts +3 -3
- package/dist/services/html/htmlGenerator.js +50 -0
- package/dist/services/html/htmlGenerator.js.map +1 -1
- package/dist/services/html/index.d.mts +43 -0
- package/dist/services/html/index.d.ts +4 -4
- package/dist/services/html/index.js +2 -1
- package/dist/services/http/apiClient.d.mts +170 -0
- package/dist/services/http/apiClient.d.ts +5 -4
- package/dist/services/http/apiClient.js +26 -0
- package/dist/services/http/apiClient.js.map +1 -1
- package/dist/services/http/http.d.mts +182 -0
- package/dist/services/http/http.d.ts +15 -8
- package/dist/services/http/http.js +63 -4
- package/dist/services/http/http.js.map +1 -1
- package/dist/services/http/index.d.mts +51 -0
- package/dist/services/http/index.d.ts +4 -3
- package/dist/services/http/index.js +4 -1
- package/dist/services/http/responsesBuilder.d.mts +179 -0
- package/dist/services/http/responsesBuilder.d.ts +4 -3
- package/dist/services/http/responsesBuilder.js +48 -1
- package/dist/services/http/responsesBuilder.js.map +1 -1
- package/dist/services/index.d.mts +33 -0
- package/dist/services/index.d.ts +4 -4
- package/dist/services/index.js +8 -0
- package/dist/services/utils/ensureBearerToken.d.mts +158 -0
- package/dist/services/utils/ensureBearerToken.d.ts +6 -5
- package/dist/services/utils/ensureBearerToken.js +16 -0
- package/dist/services/utils/ensureBearerToken.js.map +1 -1
- package/dist/services/utils/index.d.mts +44 -0
- package/dist/services/utils/index.d.ts +4 -3
- package/dist/services/utils/index.js +2 -1
- package/dist/types/events.d.mts +14 -0
- package/dist/types/events.d.ts +5 -4
- package/dist/types/express.d.mts +10 -0
- package/dist/types/express.d.ts +1 -1
- package/dist/types/http.d.mts +82 -0
- package/dist/types/http.d.ts +5 -2
- package/dist/types/http.js.map +1 -1
- package/dist/types/index.d.mts +14 -0
- package/dist/types/index.d.ts +2 -2
- package/dist/types/index.js +9 -0
- package/dist/types/options.d.mts +14 -0
- package/dist/types/options.d.ts +4 -3
- package/dist/types/utils.d.mts +48 -0
- package/dist/types/utils.d.ts +1 -1
- package/dist/types/wootils.d.mts +4 -0
- package/dist/utils/fns/index.d.mts +5 -0
- package/dist/utils/fns/index.js +7 -0
- package/dist/utils/fns/others.d.mts +17 -0
- package/dist/utils/fns/routes.d.mts +39 -0
- package/dist/utils/fns/routes.js.map +1 -1
- package/dist/utils/fns/statuses.d.mts +45 -0
- package/dist/utils/fns/statuses.d.ts +1 -1
- package/dist/utils/fns/statuses.js +4 -0
- package/dist/utils/fns/statuses.js.map +1 -1
- package/dist/utils/fns/text.d.mts +9 -0
- package/dist/utils/index.d.mts +19 -0
- package/dist/utils/index.d.ts +5 -4
- package/dist/utils/index.js +5 -0
- package/dist/utils/wrappers.d.mts +14 -0
- package/dist/utils/wrappers.d.ts +4 -3
- package/package.json +50 -49
- 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-T2T6Q22Z.js.map → chunk-F3FYYIAV.js.map} +0 -0
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import * as _homer0_jimple from '@homer0/jimple';
|
|
2
|
+
import { J as Jimpex } from '../../index-Bwf7JHu9.mjs';
|
|
3
|
+
import { Request } from 'express';
|
|
4
|
+
import { NodeFetch } from '../../types/http.mjs';
|
|
5
|
+
import { SimpleLogger } from '@homer0/simple-logger';
|
|
6
|
+
import { BodyInit, Response, RequestInit } from 'node-fetch';
|
|
7
|
+
import '../../types/express.mjs';
|
|
8
|
+
import '../../types/utils.mjs';
|
|
9
|
+
import '@homer0/path-utils';
|
|
10
|
+
import '@homer0/simple-config';
|
|
11
|
+
import '@homer0/events-hub';
|
|
12
|
+
import 'https';
|
|
13
|
+
import 'http';
|
|
14
|
+
import 'spdy';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The options to customize the service.
|
|
18
|
+
*
|
|
19
|
+
* @group Services/HTTP
|
|
20
|
+
*/
|
|
21
|
+
type HTTPOptions = {
|
|
22
|
+
/**
|
|
23
|
+
* Whether or not the service should log the requests and their responses.
|
|
24
|
+
*/
|
|
25
|
+
logRequests?: boolean;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* The options to construct a {@link HTTP}.
|
|
29
|
+
*
|
|
30
|
+
* @group Services/HTTP
|
|
31
|
+
*/
|
|
32
|
+
type HTTPContructorOptions = Partial<HTTPOptions> & {
|
|
33
|
+
/**
|
|
34
|
+
* A dictionary with the dependencies to inject.
|
|
35
|
+
*/
|
|
36
|
+
inject: {
|
|
37
|
+
logger: SimpleLogger;
|
|
38
|
+
nodeFetch: NodeFetch;
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* The allowed formats for the body of a request.
|
|
43
|
+
*
|
|
44
|
+
* @group Services/HTTP
|
|
45
|
+
*/
|
|
46
|
+
type HTTPFetchBody = string | Record<string | number, unknown> | BodyInit;
|
|
47
|
+
/**
|
|
48
|
+
* The options for a request.
|
|
49
|
+
*
|
|
50
|
+
* @group Services/HTTP
|
|
51
|
+
*/
|
|
52
|
+
type HTTPFetchOptions = {
|
|
53
|
+
/**
|
|
54
|
+
* The HTTP method.
|
|
55
|
+
*
|
|
56
|
+
* @default 'GET'
|
|
57
|
+
*/
|
|
58
|
+
method?: string;
|
|
59
|
+
/**
|
|
60
|
+
* The headers dictionary.
|
|
61
|
+
*/
|
|
62
|
+
headers?: Record<string, string>;
|
|
63
|
+
/**
|
|
64
|
+
* The body of the request.
|
|
65
|
+
*/
|
|
66
|
+
body?: HTTPFetchBody;
|
|
67
|
+
/**
|
|
68
|
+
* A dictionary of query string parameters.
|
|
69
|
+
*/
|
|
70
|
+
qs?: Record<string, unknown>;
|
|
71
|
+
/**
|
|
72
|
+
* A request object generated by the application. This can be used to copy information
|
|
73
|
+
* like custom headers or the IP (for the X-Forwarded-For header).
|
|
74
|
+
*/
|
|
75
|
+
req?: Request;
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* The options for the method that extracts custom headers from a request.
|
|
79
|
+
*
|
|
80
|
+
* @group Services/HTTP
|
|
81
|
+
*/
|
|
82
|
+
type GetCustomHeadersFromRequestOptions = {
|
|
83
|
+
/**
|
|
84
|
+
* Since the method considers all headers that start with `x-` as custom headers,
|
|
85
|
+
* setting this to `false` is the only way to exclude `x-forwarded-` headers from the
|
|
86
|
+
* list.
|
|
87
|
+
*
|
|
88
|
+
* @default false
|
|
89
|
+
*/
|
|
90
|
+
includeXForwardedHeaders?: boolean;
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* A set of utilities to work with HTTP requests and responses.
|
|
94
|
+
*
|
|
95
|
+
* @group Services
|
|
96
|
+
* @group Services/HTTP
|
|
97
|
+
*/
|
|
98
|
+
declare class HTTP {
|
|
99
|
+
/**
|
|
100
|
+
* The service used to log information in the terminal.
|
|
101
|
+
*/
|
|
102
|
+
protected readonly _logger: SimpleLogger;
|
|
103
|
+
/**
|
|
104
|
+
* The node-fetch library. Since it's an ESM only module, Jimpex loads it on boot and makes
|
|
105
|
+
* it available on the container.
|
|
106
|
+
*/
|
|
107
|
+
protected readonly _nodeFetch: NodeFetch;
|
|
108
|
+
/**
|
|
109
|
+
* The service customization options.
|
|
110
|
+
*/
|
|
111
|
+
protected readonly _options: HTTPOptions;
|
|
112
|
+
/**
|
|
113
|
+
* @param options The options to construct the class.
|
|
114
|
+
*/
|
|
115
|
+
constructor({ inject: { logger, nodeFetch }, ...options }: HTTPContructorOptions);
|
|
116
|
+
/**
|
|
117
|
+
* Makes a fetch request.
|
|
118
|
+
*
|
|
119
|
+
* @param url The URL to fetch.
|
|
120
|
+
* @param options The custom options for the request.
|
|
121
|
+
*/
|
|
122
|
+
fetch(url: string, options?: HTTPFetchOptions): Promise<Response>;
|
|
123
|
+
/**
|
|
124
|
+
* Tries to get the IP address from a given request.
|
|
125
|
+
*
|
|
126
|
+
* @param req The request from which it will try to obtain the IP address.
|
|
127
|
+
*/
|
|
128
|
+
getIPFromRequest(req: Request): string | undefined;
|
|
129
|
+
/**
|
|
130
|
+
* Creates a dictionary with all the custom headers a request has. By custom header it
|
|
131
|
+
* means all the headers which name start with `x-`.
|
|
132
|
+
*
|
|
133
|
+
* @param req The request from which it will try to get the headers.
|
|
134
|
+
* @param options The options to customize the behavior with certain headers.
|
|
135
|
+
*/
|
|
136
|
+
getCustomHeadersFromRequest(req: Request, options?: GetCustomHeadersFromRequestOptions): Record<string, string>;
|
|
137
|
+
/**
|
|
138
|
+
* It takes a dictionary of headers and normalize the names so each word will start with
|
|
139
|
+
* an upper case character. This is helpful in case you added custom headers and didn't
|
|
140
|
+
* care about the casing, or when copying headers from a server request, as they all
|
|
141
|
+
* come tranformed into lower case.
|
|
142
|
+
*
|
|
143
|
+
* @param headers The dictionary of headers to normalize.
|
|
144
|
+
*/
|
|
145
|
+
normalizeHeaders(headers: Record<string, string>): Record<string, string>;
|
|
146
|
+
/**
|
|
147
|
+
* The customization options.
|
|
148
|
+
*/
|
|
149
|
+
get options(): Readonly<HTTPOptions>;
|
|
150
|
+
/**
|
|
151
|
+
* Logs a request information into the terminal.
|
|
152
|
+
*
|
|
153
|
+
* @param url The request URL.
|
|
154
|
+
* @param options The options for the request.
|
|
155
|
+
*/
|
|
156
|
+
protected _logRequest(url: string, options: RequestInit): void;
|
|
157
|
+
/**
|
|
158
|
+
* Logs a response information into the terminal.
|
|
159
|
+
*
|
|
160
|
+
* @param response The response to log.
|
|
161
|
+
*/
|
|
162
|
+
protected _logResponse(response: Response): void;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* The service provider that once registered on the container will set an instance of
|
|
166
|
+
* {@link HTTP} as the `http` service. The provider also checks the `debug.logRequests`
|
|
167
|
+
* setting on the application configuration in order to enable or not the logging of
|
|
168
|
+
* requests/responses.
|
|
169
|
+
*
|
|
170
|
+
* @example
|
|
171
|
+
*
|
|
172
|
+
* // Register it on the container
|
|
173
|
+
* container.register(httpProvider);
|
|
174
|
+
* // Getting access to the service instance
|
|
175
|
+
* const http = container.get<HTTP>('http');
|
|
176
|
+
*
|
|
177
|
+
* @group Providers
|
|
178
|
+
* @group Services/HTTP
|
|
179
|
+
*/
|
|
180
|
+
declare const httpProvider: _homer0_jimple.Resource<"provider", "register", _homer0_jimple.ProviderRegisterFn<Jimpex>>;
|
|
181
|
+
|
|
182
|
+
export { type GetCustomHeadersFromRequestOptions, HTTP, type HTTPContructorOptions, type HTTPFetchBody, type HTTPFetchOptions, type HTTPOptions, httpProvider };
|
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import * as _homer0_jimple from '@homer0/jimple';
|
|
2
|
-
import { J as Jimpex } from '../../
|
|
2
|
+
import { J as Jimpex } from '../../index-C6I3NCC-.js';
|
|
3
3
|
import { Request } from 'express';
|
|
4
|
-
import {
|
|
4
|
+
import { NodeFetch } from '../../types/http.js';
|
|
5
5
|
import { SimpleLogger } from '@homer0/simple-logger';
|
|
6
|
-
import '
|
|
6
|
+
import { BodyInit, Response, RequestInit } from 'node-fetch';
|
|
7
7
|
import '../../types/express.js';
|
|
8
|
-
import '../../types/
|
|
8
|
+
import '../../types/utils.js';
|
|
9
|
+
import '@homer0/path-utils';
|
|
10
|
+
import '@homer0/simple-config';
|
|
11
|
+
import '@homer0/events-hub';
|
|
9
12
|
import 'https';
|
|
10
13
|
import 'http';
|
|
11
14
|
import 'spdy';
|
|
12
|
-
import '@homer0/simple-config';
|
|
13
|
-
import '../../types/utils.js';
|
|
14
15
|
|
|
15
16
|
/**
|
|
16
17
|
* The options to customize the service.
|
|
@@ -34,6 +35,7 @@ type HTTPContructorOptions = Partial<HTTPOptions> & {
|
|
|
34
35
|
*/
|
|
35
36
|
inject: {
|
|
36
37
|
logger: SimpleLogger;
|
|
38
|
+
nodeFetch: NodeFetch;
|
|
37
39
|
};
|
|
38
40
|
};
|
|
39
41
|
/**
|
|
@@ -98,6 +100,11 @@ declare class HTTP {
|
|
|
98
100
|
* The service used to log information in the terminal.
|
|
99
101
|
*/
|
|
100
102
|
protected readonly _logger: SimpleLogger;
|
|
103
|
+
/**
|
|
104
|
+
* The node-fetch library. Since it's an ESM only module, Jimpex loads it on boot and makes
|
|
105
|
+
* it available on the container.
|
|
106
|
+
*/
|
|
107
|
+
protected readonly _nodeFetch: NodeFetch;
|
|
101
108
|
/**
|
|
102
109
|
* The service customization options.
|
|
103
110
|
*/
|
|
@@ -105,7 +112,7 @@ declare class HTTP {
|
|
|
105
112
|
/**
|
|
106
113
|
* @param options The options to construct the class.
|
|
107
114
|
*/
|
|
108
|
-
constructor({ inject: { logger }, ...options }: HTTPContructorOptions);
|
|
115
|
+
constructor({ inject: { logger, nodeFetch }, ...options }: HTTPContructorOptions);
|
|
109
116
|
/**
|
|
110
117
|
* Makes a fetch request.
|
|
111
118
|
*
|
|
@@ -172,4 +179,4 @@ declare class HTTP {
|
|
|
172
179
|
*/
|
|
173
180
|
declare const httpProvider: _homer0_jimple.Resource<"provider", "register", _homer0_jimple.ProviderRegisterFn<Jimpex>>;
|
|
174
181
|
|
|
175
|
-
export { GetCustomHeadersFromRequestOptions, HTTP, HTTPContructorOptions, HTTPFetchBody, HTTPFetchOptions, HTTPOptions, httpProvider };
|
|
182
|
+
export { type GetCustomHeadersFromRequestOptions, HTTP, type HTTPContructorOptions, type HTTPFetchBody, type HTTPFetchOptions, type HTTPOptions, httpProvider };
|
|
@@ -19,6 +19,10 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
19
19
|
return to;
|
|
20
20
|
};
|
|
21
21
|
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
22
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
23
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
24
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
25
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
22
26
|
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
23
27
|
mod
|
|
24
28
|
));
|
|
@@ -33,15 +37,29 @@ __export(http_exports, {
|
|
|
33
37
|
httpProvider: () => httpProvider
|
|
34
38
|
});
|
|
35
39
|
module.exports = __toCommonJS(http_exports);
|
|
36
|
-
var import_node_fetch = __toESM(require("node-fetch"));
|
|
37
40
|
var import_urijs = __toESM(require("urijs"));
|
|
38
41
|
var import_deep_assign = require("@homer0/deep-assign");
|
|
39
42
|
var import_utils = require("../../utils");
|
|
40
43
|
class HTTP {
|
|
41
|
-
|
|
44
|
+
/**
|
|
45
|
+
* @param options The options to construct the class.
|
|
46
|
+
*/
|
|
47
|
+
constructor({ inject: { logger, nodeFetch }, ...options }) {
|
|
48
|
+
/**
|
|
49
|
+
* The service used to log information in the terminal.
|
|
50
|
+
*/
|
|
42
51
|
__publicField(this, "_logger");
|
|
52
|
+
/**
|
|
53
|
+
* The node-fetch library. Since it's an ESM only module, Jimpex loads it on boot and makes
|
|
54
|
+
* it available on the container.
|
|
55
|
+
*/
|
|
56
|
+
__publicField(this, "_nodeFetch");
|
|
57
|
+
/**
|
|
58
|
+
* The service customization options.
|
|
59
|
+
*/
|
|
43
60
|
__publicField(this, "_options");
|
|
44
61
|
this._logger = logger;
|
|
62
|
+
this._nodeFetch = nodeFetch;
|
|
45
63
|
this._options = (0, import_deep_assign.deepAssignWithOverwrite)(
|
|
46
64
|
{
|
|
47
65
|
logRequests: false
|
|
@@ -50,6 +68,12 @@ class HTTP {
|
|
|
50
68
|
);
|
|
51
69
|
this.fetch = this.fetch.bind(this);
|
|
52
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* Makes a fetch request.
|
|
73
|
+
*
|
|
74
|
+
* @param url The URL to fetch.
|
|
75
|
+
* @param options The custom options for the request.
|
|
76
|
+
*/
|
|
53
77
|
async fetch(url, options = {}) {
|
|
54
78
|
let useURL = url;
|
|
55
79
|
if (options.qs) {
|
|
@@ -78,12 +102,17 @@ class HTTP {
|
|
|
78
102
|
if (logRequests) {
|
|
79
103
|
this._logRequest(useURL, fetchOptions);
|
|
80
104
|
}
|
|
81
|
-
const response = await
|
|
105
|
+
const response = await this._nodeFetch(useURL, fetchOptions);
|
|
82
106
|
if (logRequests) {
|
|
83
107
|
this._logResponse(response);
|
|
84
108
|
}
|
|
85
109
|
return response;
|
|
86
110
|
}
|
|
111
|
+
/**
|
|
112
|
+
* Tries to get the IP address from a given request.
|
|
113
|
+
*
|
|
114
|
+
* @param req The request from which it will try to obtain the IP address.
|
|
115
|
+
*/
|
|
87
116
|
getIPFromRequest(req) {
|
|
88
117
|
const headerValue = req.headers["x-forwarded-for"];
|
|
89
118
|
if (headerValue) {
|
|
@@ -91,6 +120,13 @@ class HTTP {
|
|
|
91
120
|
}
|
|
92
121
|
return req?.connection?.remoteAddress || req?.socket?.remoteAddress;
|
|
93
122
|
}
|
|
123
|
+
/**
|
|
124
|
+
* Creates a dictionary with all the custom headers a request has. By custom header it
|
|
125
|
+
* means all the headers which name start with `x-`.
|
|
126
|
+
*
|
|
127
|
+
* @param req The request from which it will try to get the headers.
|
|
128
|
+
* @param options The options to customize the behavior with certain headers.
|
|
129
|
+
*/
|
|
94
130
|
getCustomHeadersFromRequest(req, options = {}) {
|
|
95
131
|
const { includeXForwardedHeaders = false } = options;
|
|
96
132
|
return Object.keys(req.headers).reduce((acc, headerName) => {
|
|
@@ -100,6 +136,14 @@ class HTTP {
|
|
|
100
136
|
return acc;
|
|
101
137
|
}, {});
|
|
102
138
|
}
|
|
139
|
+
/**
|
|
140
|
+
* It takes a dictionary of headers and normalize the names so each word will start with
|
|
141
|
+
* an upper case character. This is helpful in case you added custom headers and didn't
|
|
142
|
+
* care about the casing, or when copying headers from a server request, as they all
|
|
143
|
+
* come tranformed into lower case.
|
|
144
|
+
*
|
|
145
|
+
* @param headers The dictionary of headers to normalize.
|
|
146
|
+
*/
|
|
103
147
|
normalizeHeaders(headers) {
|
|
104
148
|
return Object.keys(headers).reduce((acc, name) => {
|
|
105
149
|
const newName = name.split("-").map((part) => part.replace(/^(\w)/, (_, letter) => letter.toUpperCase())).join("-");
|
|
@@ -107,9 +151,18 @@ class HTTP {
|
|
|
107
151
|
return acc;
|
|
108
152
|
}, {});
|
|
109
153
|
}
|
|
154
|
+
/**
|
|
155
|
+
* The customization options.
|
|
156
|
+
*/
|
|
110
157
|
get options() {
|
|
111
158
|
return (0, import_deep_assign.deepAssignWithOverwrite)({}, this._options);
|
|
112
159
|
}
|
|
160
|
+
/**
|
|
161
|
+
* Logs a request information into the terminal.
|
|
162
|
+
*
|
|
163
|
+
* @param url The request URL.
|
|
164
|
+
* @param options The options for the request.
|
|
165
|
+
*/
|
|
113
166
|
_logRequest(url, options) {
|
|
114
167
|
const { method, headers } = options;
|
|
115
168
|
const prefix = "REQUEST> ";
|
|
@@ -125,6 +178,11 @@ class HTTP {
|
|
|
125
178
|
}
|
|
126
179
|
this._logger.info(lines);
|
|
127
180
|
}
|
|
181
|
+
/**
|
|
182
|
+
* Logs a response information into the terminal.
|
|
183
|
+
*
|
|
184
|
+
* @param response The response to log.
|
|
185
|
+
*/
|
|
128
186
|
_logResponse(response) {
|
|
129
187
|
const prefix = "RESPONSE> ";
|
|
130
188
|
const lines = [
|
|
@@ -144,7 +202,8 @@ const httpProvider = (0, import_utils.provider)((app) => {
|
|
|
144
202
|
const logRequests = config.get("debug.logRequests") === true;
|
|
145
203
|
return new HTTP({
|
|
146
204
|
inject: {
|
|
147
|
-
logger: app.get("logger")
|
|
205
|
+
logger: app.get("logger"),
|
|
206
|
+
nodeFetch: app.get("node-fetch")
|
|
148
207
|
},
|
|
149
208
|
logRequests
|
|
150
209
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/http/http.ts"],"sourcesContent":["import fetch, { type RequestInit, type BodyInit } from 'node-fetch';\nimport urijs from 'urijs';\nimport { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport { provider } from '../../utils';\nimport { Logger, Request, HTTPResponse } from '../../types';\n/**\n * The options to customize the service.\n *\n * @group Services/HTTP\n */\nexport type HTTPOptions = {\n /**\n * Whether or not the service should log the requests and their responses.\n */\n logRequests?: boolean;\n};\n/**\n * The options to construct a {@link HTTP}.\n *\n * @group Services/HTTP\n */\nexport type HTTPContructorOptions = Partial<HTTPOptions> & {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n logger: Logger;\n };\n};\n/**\n * The allowed formats for the body of a request.\n *\n * @group Services/HTTP\n */\nexport type HTTPFetchBody = string | Record<string | number, unknown> | BodyInit;\n/**\n * The options for a request.\n *\n * @group Services/HTTP\n */\nexport type HTTPFetchOptions = {\n /**\n * The HTTP method.\n *\n * @default 'GET'\n */\n method?: string;\n /**\n * The headers dictionary.\n */\n headers?: Record<string, string>;\n /**\n * The body of the request.\n */\n body?: HTTPFetchBody;\n /**\n * A dictionary of query string parameters.\n */\n qs?: Record<string, unknown>;\n /**\n * A request object generated by the application. This can be used to copy information\n * like custom headers or the IP (for the X-Forwarded-For header).\n */\n req?: Request;\n};\n/**\n * The options for the method that extracts custom headers from a request.\n *\n * @group Services/HTTP\n */\nexport type GetCustomHeadersFromRequestOptions = {\n /**\n * Since the method considers all headers that start with `x-` as custom headers,\n * setting this to `false` is the only way to exclude `x-forwarded-` headers from the\n * list.\n *\n * @default false\n */\n includeXForwardedHeaders?: boolean;\n};\n/**\n * A set of utilities to work with HTTP requests and responses.\n *\n * @group Services\n * @group Services/HTTP\n */\nexport class HTTP {\n /**\n * The service used to log information in the terminal.\n */\n protected readonly _logger: Logger;\n /**\n * The service customization options.\n */\n protected readonly _options: HTTPOptions;\n /**\n * @param options The options to construct the class.\n */\n constructor({ inject: { logger }, ...options }: HTTPContructorOptions) {\n this._logger = logger;\n this._options = deepAssignWithOverwrite(\n {\n logRequests: false,\n },\n options,\n );\n\n this.fetch = this.fetch.bind(this);\n }\n /**\n * Makes a fetch request.\n *\n * @param url The URL to fetch.\n * @param options The custom options for the request.\n */\n async fetch(url: string, options: HTTPFetchOptions = {}): Promise<HTTPResponse> {\n let useURL = url;\n if (options.qs) {\n useURL = urijs(url).query(options.qs).toString();\n }\n\n const fetchOptions: RequestInit = {\n method: (options.method || 'get').toUpperCase(),\n body: options.body as BodyInit,\n };\n\n let defaultHeaders: Record<string, string> | undefined;\n if (options.req) {\n defaultHeaders = this.getCustomHeadersFromRequest(options.req);\n const ip = this.getIPFromRequest(options.req);\n if (ip) {\n defaultHeaders['x-forwarded-for'] = ip;\n }\n }\n const headers = {\n ...defaultHeaders,\n ...options.headers,\n };\n\n if (Object.keys(headers).length) {\n fetchOptions.headers = this.normalizeHeaders(headers);\n }\n\n const { logRequests } = this._options;\n if (logRequests) {\n this._logRequest(useURL, fetchOptions);\n }\n\n const response = await fetch(useURL, fetchOptions);\n if (logRequests) {\n this._logResponse(response);\n }\n\n return response;\n }\n /**\n * Tries to get the IP address from a given request.\n *\n * @param req The request from which it will try to obtain the IP address.\n */\n getIPFromRequest(req: Request): string | undefined {\n const headerValue = req.headers['x-forwarded-for'];\n if (headerValue) {\n return String(headerValue);\n }\n\n return req?.connection?.remoteAddress || req?.socket?.remoteAddress;\n }\n /**\n * Creates a dictionary with all the custom headers a request has. By custom header it\n * means all the headers which name start with `x-`.\n *\n * @param req The request from which it will try to get the headers.\n * @param options The options to customize the behavior with certain headers.\n */\n getCustomHeadersFromRequest(\n req: Request,\n options: GetCustomHeadersFromRequestOptions = {},\n ): Record<string, string> {\n const { includeXForwardedHeaders = false } = options;\n return Object.keys(req.headers).reduce<Record<string, string>>((acc, headerName) => {\n if (\n headerName.startsWith('x-') &&\n (includeXForwardedHeaders || !headerName.startsWith('x-forwarded-'))\n ) {\n acc[headerName] = req.headers[headerName] as string;\n }\n return acc;\n }, {});\n }\n /**\n * It takes a dictionary of headers and normalize the names so each word will start with\n * an upper case character. This is helpful in case you added custom headers and didn't\n * care about the casing, or when copying headers from a server request, as they all\n * come tranformed into lower case.\n *\n * @param headers The dictionary of headers to normalize.\n */\n normalizeHeaders(headers: Record<string, string>): Record<string, string> {\n return Object.keys(headers).reduce<Record<string, string>>((acc, name) => {\n const newName = name\n .split('-')\n .map((part) => part.replace(/^(\\w)/, (_, letter) => letter.toUpperCase()))\n .join('-');\n\n acc[newName] = headers[name]!;\n return acc;\n }, {});\n }\n /**\n * The customization options.\n */\n get options(): Readonly<HTTPOptions> {\n return deepAssignWithOverwrite({}, this._options);\n }\n /**\n * Logs a request information into the terminal.\n *\n * @param url The request URL.\n * @param options The options for the request.\n */\n protected _logRequest(url: string, options: RequestInit): void {\n const { method, headers } = options;\n const prefix = 'REQUEST> ';\n const lines = ['--->>', `${prefix}${method} ${url}`];\n if (headers) {\n Object.keys(headers).forEach((header) => {\n const value = headers[header as keyof typeof headers];\n lines.push(`${prefix}${header}: ${value}`);\n });\n }\n\n if (options.body) {\n lines.push(`${prefix}body: \"${options.body}\"`);\n }\n\n this._logger.info(lines);\n }\n /**\n * Logs a response information into the terminal.\n *\n * @param response The response to log.\n */\n protected _logResponse(response: HTTPResponse) {\n const prefix = 'RESPONSE> ';\n const lines = [\n '<<---',\n `${prefix}${response.url}`,\n `${prefix}status: ${response.status}`,\n ];\n\n response.headers.forEach((value, header) => {\n lines.push(`${prefix}${header}: ${value}`);\n });\n\n this._logger.info(lines);\n }\n}\n/**\n * The service provider that once registered on the container will set an instance of\n * {@link HTTP} as the `http` service. The provider also checks the `debug.logRequests`\n * setting on the application configuration in order to enable or not the logging of\n * requests/responses.\n *\n * @example\n *\n * // Register it on the container\n * container.register(httpProvider);\n * // Getting access to the service instance\n * const http = container.get<HTTP>('http');\n *\n * @group Providers\n * @group Services/HTTP\n */\nexport const httpProvider = provider((app) => {\n app.set('http', () => {\n const config = app.getConfig();\n const logRequests = config.get<boolean | undefined>('debug.logRequests') === true;\n return new HTTP({\n inject: {\n logger: app.get('logger'),\n },\n logRequests,\n });\n });\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAuD;AACvD,mBAAkB;AAClB,yBAAwC;AACxC,mBAAyB;AAmFlB,MAAM,KAAK;AAAA,EAYhB,YAAY,EAAE,QAAQ,EAAE,OAAO,MAAM,QAAQ,GAA0B;AARvE,wBAAmB;AAInB,wBAAmB;AAKjB,SAAK,UAAU;AACf,SAAK,eAAW;AAAA,MACd;AAAA,QACE,aAAa;AAAA,MACf;AAAA,MACA;AAAA,IACF;AAEA,SAAK,QAAQ,KAAK,MAAM,KAAK,IAAI;AAAA,EACnC;AAAA,EAOA,MAAM,MAAM,KAAa,UAA4B,CAAC,GAA0B;AAC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I,IAAI,QAAQ,MAAM;AACpB,UAAM,SAAS,IAAI,UAAU;AAC7B,UAAM,cAAc,OAAO,IAAyB,mBAAmB,MAAM;AAC7E,WAAO,IAAI,KAAK;AAAA,MACd,QAAQ;AAAA,QACN,QAAQ,IAAI,IAAI,QAAQ;AAAA,MAC1B;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACH,CAAC;","names":["urijs","fetch"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/services/http/http.ts"],"sourcesContent":["import urijs from 'urijs';\nimport type { RequestInit, BodyInit } from 'node-fetch';\nimport { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport { provider } from '../../utils';\nimport { Logger, Request, HTTPResponse, NodeFetch } from '../../types';\n\n/**\n * The options to customize the service.\n *\n * @group Services/HTTP\n */\nexport type HTTPOptions = {\n /**\n * Whether or not the service should log the requests and their responses.\n */\n logRequests?: boolean;\n};\n/**\n * The options to construct a {@link HTTP}.\n *\n * @group Services/HTTP\n */\nexport type HTTPContructorOptions = Partial<HTTPOptions> & {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n logger: Logger;\n nodeFetch: NodeFetch;\n };\n};\n/**\n * The allowed formats for the body of a request.\n *\n * @group Services/HTTP\n */\nexport type HTTPFetchBody = string | Record<string | number, unknown> | BodyInit;\n/**\n * The options for a request.\n *\n * @group Services/HTTP\n */\nexport type HTTPFetchOptions = {\n /**\n * The HTTP method.\n *\n * @default 'GET'\n */\n method?: string;\n /**\n * The headers dictionary.\n */\n headers?: Record<string, string>;\n /**\n * The body of the request.\n */\n body?: HTTPFetchBody;\n /**\n * A dictionary of query string parameters.\n */\n qs?: Record<string, unknown>;\n /**\n * A request object generated by the application. This can be used to copy information\n * like custom headers or the IP (for the X-Forwarded-For header).\n */\n req?: Request;\n};\n/**\n * The options for the method that extracts custom headers from a request.\n *\n * @group Services/HTTP\n */\nexport type GetCustomHeadersFromRequestOptions = {\n /**\n * Since the method considers all headers that start with `x-` as custom headers,\n * setting this to `false` is the only way to exclude `x-forwarded-` headers from the\n * list.\n *\n * @default false\n */\n includeXForwardedHeaders?: boolean;\n};\n/**\n * A set of utilities to work with HTTP requests and responses.\n *\n * @group Services\n * @group Services/HTTP\n */\nexport class HTTP {\n /**\n * The service used to log information in the terminal.\n */\n protected readonly _logger: Logger;\n /**\n * The node-fetch 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 _nodeFetch: NodeFetch;\n /**\n * The service customization options.\n */\n protected readonly _options: HTTPOptions;\n /**\n * @param options The options to construct the class.\n */\n constructor({ inject: { logger, nodeFetch }, ...options }: HTTPContructorOptions) {\n this._logger = logger;\n this._nodeFetch = nodeFetch;\n this._options = deepAssignWithOverwrite(\n {\n logRequests: false,\n },\n options,\n );\n\n this.fetch = this.fetch.bind(this);\n }\n /**\n * Makes a fetch request.\n *\n * @param url The URL to fetch.\n * @param options The custom options for the request.\n */\n async fetch(url: string, options: HTTPFetchOptions = {}): Promise<HTTPResponse> {\n let useURL = url;\n if (options.qs) {\n useURL = urijs(url).query(options.qs).toString();\n }\n\n const fetchOptions: RequestInit = {\n method: (options.method || 'get').toUpperCase(),\n body: options.body as BodyInit,\n };\n\n let defaultHeaders: Record<string, string> | undefined;\n if (options.req) {\n defaultHeaders = this.getCustomHeadersFromRequest(options.req);\n const ip = this.getIPFromRequest(options.req);\n if (ip) {\n defaultHeaders['x-forwarded-for'] = ip;\n }\n }\n const headers = {\n ...defaultHeaders,\n ...options.headers,\n };\n\n if (Object.keys(headers).length) {\n fetchOptions.headers = this.normalizeHeaders(headers);\n }\n\n const { logRequests } = this._options;\n if (logRequests) {\n this._logRequest(useURL, fetchOptions);\n }\n\n const response = await this._nodeFetch(useURL, fetchOptions);\n if (logRequests) {\n this._logResponse(response);\n }\n\n return response;\n }\n /**\n * Tries to get the IP address from a given request.\n *\n * @param req The request from which it will try to obtain the IP address.\n */\n getIPFromRequest(req: Request): string | undefined {\n const headerValue = req.headers['x-forwarded-for'];\n if (headerValue) {\n return String(headerValue);\n }\n\n return req?.connection?.remoteAddress || req?.socket?.remoteAddress;\n }\n /**\n * Creates a dictionary with all the custom headers a request has. By custom header it\n * means all the headers which name start with `x-`.\n *\n * @param req The request from which it will try to get the headers.\n * @param options The options to customize the behavior with certain headers.\n */\n getCustomHeadersFromRequest(\n req: Request,\n options: GetCustomHeadersFromRequestOptions = {},\n ): Record<string, string> {\n const { includeXForwardedHeaders = false } = options;\n return Object.keys(req.headers).reduce<Record<string, string>>((acc, headerName) => {\n if (\n headerName.startsWith('x-') &&\n (includeXForwardedHeaders || !headerName.startsWith('x-forwarded-'))\n ) {\n acc[headerName] = req.headers[headerName] as string;\n }\n return acc;\n }, {});\n }\n /**\n * It takes a dictionary of headers and normalize the names so each word will start with\n * an upper case character. This is helpful in case you added custom headers and didn't\n * care about the casing, or when copying headers from a server request, as they all\n * come tranformed into lower case.\n *\n * @param headers The dictionary of headers to normalize.\n */\n normalizeHeaders(headers: Record<string, string>): Record<string, string> {\n return Object.keys(headers).reduce<Record<string, string>>((acc, name) => {\n const newName = name\n .split('-')\n .map((part) => part.replace(/^(\\w)/, (_, letter) => letter.toUpperCase()))\n .join('-');\n\n acc[newName] = headers[name]!;\n return acc;\n }, {});\n }\n /**\n * The customization options.\n */\n get options(): Readonly<HTTPOptions> {\n return deepAssignWithOverwrite({}, this._options);\n }\n /**\n * Logs a request information into the terminal.\n *\n * @param url The request URL.\n * @param options The options for the request.\n */\n protected _logRequest(url: string, options: RequestInit): void {\n const { method, headers } = options;\n const prefix = 'REQUEST> ';\n const lines = ['--->>', `${prefix}${method} ${url}`];\n if (headers) {\n Object.keys(headers).forEach((header) => {\n const value = headers[header as keyof typeof headers];\n lines.push(`${prefix}${header}: ${value}`);\n });\n }\n\n if (options.body) {\n lines.push(`${prefix}body: \"${options.body}\"`);\n }\n\n this._logger.info(lines);\n }\n /**\n * Logs a response information into the terminal.\n *\n * @param response The response to log.\n */\n protected _logResponse(response: HTTPResponse) {\n const prefix = 'RESPONSE> ';\n const lines = [\n '<<---',\n `${prefix}${response.url}`,\n `${prefix}status: ${response.status}`,\n ];\n\n response.headers.forEach((value, header) => {\n lines.push(`${prefix}${header}: ${value}`);\n });\n\n this._logger.info(lines);\n }\n}\n/**\n * The service provider that once registered on the container will set an instance of\n * {@link HTTP} as the `http` service. The provider also checks the `debug.logRequests`\n * setting on the application configuration in order to enable or not the logging of\n * requests/responses.\n *\n * @example\n *\n * // Register it on the container\n * container.register(httpProvider);\n * // Getting access to the service instance\n * const http = container.get<HTTP>('http');\n *\n * @group Providers\n * @group Services/HTTP\n */\nexport const httpProvider = provider((app) => {\n app.set('http', () => {\n const config = app.getConfig();\n const logRequests = config.get<boolean | undefined>('debug.logRequests') === true;\n return new HTTP({\n inject: {\n logger: app.get('logger'),\n nodeFetch: app.get('node-fetch'),\n },\n logRequests,\n });\n });\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AAElB,yBAAwC;AACxC,mBAAyB;AAqFlB,MAAM,KAAK;AAAA;AAAA;AAAA;AAAA,EAiBhB,YAAY,EAAE,QAAQ,EAAE,QAAQ,UAAU,GAAG,GAAG,QAAQ,GAA0B;AAblF;AAAA;AAAA;AAAA,wBAAmB;AAKnB;AAAA;AAAA;AAAA;AAAA,wBAAmB;AAInB;AAAA;AAAA;AAAA,wBAAmB;AAKjB,SAAK,UAAU;AACf,SAAK,aAAa;AAClB,SAAK,eAAW;AAAA,MACd;AAAA,QACE,aAAa;AAAA,MACf;AAAA,MACA;AAAA,IACF;AAEA,SAAK,QAAQ,KAAK,MAAM,KAAK,IAAI;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,MAAM,KAAa,UAA4B,CAAC,GAA0B;AAC9E,QAAI,SAAS;AACb,QAAI,QAAQ,IAAI;AACd,mBAAS,aAAAA,SAAM,GAAG,EAAE,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AAM,WAAW,SAAS,MAAM;AAAA,IACrC;AAEA,aAAS,QAAQ,QAAQ,CAAC,OAAO,WAAW;AAC1C,YAAM,KAAK,GAAG,MAAM,GAAG,MAAM,KAAK,KAAK,EAAE;AAAA,IAC3C,CAAC;AAED,SAAK,QAAQ,KAAK,KAAK;AAAA,EACzB;AACF;AAiBO,MAAM,mBAAe,uBAAS,CAAC,QAAQ;AAC5C,MAAI,IAAI,QAAQ,MAAM;AACpB,UAAM,SAAS,IAAI,UAAU;AAC7B,UAAM,cAAc,OAAO,IAAyB,mBAAmB,MAAM;AAC7E,WAAO,IAAI,KAAK;AAAA,MACd,QAAQ;AAAA,QACN,QAAQ,IAAI,IAAI,QAAQ;AAAA,QACxB,WAAW,IAAI,IAAI,YAAY;AAAA,MACjC;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACH,CAAC;","names":["urijs"]}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import * as _homer0_jimple from '@homer0/jimple';
|
|
2
|
+
import { J as Jimpex } from '../../index-Bwf7JHu9.mjs';
|
|
3
|
+
export { ErrorResponse } from '@homer0/api-utils';
|
|
4
|
+
import { APIClientProviderOptions } from './apiClient.mjs';
|
|
5
|
+
export { APIClient, APIClientConfig, APIClientConstructorOptions, APIClientSettings, EndpointsType, apiClientProvider } from './apiClient.mjs';
|
|
6
|
+
export { GetCustomHeadersFromRequestOptions, HTTP, HTTPContructorOptions, HTTPFetchBody, HTTPFetchOptions, HTTPOptions, httpProvider } from './http.mjs';
|
|
7
|
+
export { HTMLPostMessageResponseOptions, JSONResponseOptions, ResponsesBuilder, ResponsesBuilderConstructorOptions, responsesBuilderProvider } from './responsesBuilder.mjs';
|
|
8
|
+
import '../../types/express.mjs';
|
|
9
|
+
import 'express';
|
|
10
|
+
import '../../types/http.mjs';
|
|
11
|
+
import 'https';
|
|
12
|
+
import 'http';
|
|
13
|
+
import 'spdy';
|
|
14
|
+
import 'node-fetch';
|
|
15
|
+
import '../../types/utils.mjs';
|
|
16
|
+
import '@homer0/path-utils';
|
|
17
|
+
import '@homer0/simple-logger';
|
|
18
|
+
import '@homer0/simple-config';
|
|
19
|
+
import '@homer0/events-hub';
|
|
20
|
+
import '../common/httpError.mjs';
|
|
21
|
+
import '../../utils/fns/statuses.mjs';
|
|
22
|
+
import 'statuses';
|
|
23
|
+
import '../common/appError.mjs';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Registers all the HTTP services on the container.
|
|
27
|
+
*
|
|
28
|
+
* - {@link APIClient | apiClient}
|
|
29
|
+
* - {@link HTTP | http}
|
|
30
|
+
* - {@link ResponsesBuilder | responsesBuilder}
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
*
|
|
34
|
+
* // Register the collection on the container
|
|
35
|
+
* container.register(httpServicesProvider);
|
|
36
|
+
* // Getting access to one the services instance
|
|
37
|
+
* const apiClient = container.get<APIClient>('apiClient');
|
|
38
|
+
*
|
|
39
|
+
* @group Providers
|
|
40
|
+
*/
|
|
41
|
+
declare const httpServicesProvider: {
|
|
42
|
+
apiClientProvider: _homer0_jimple.ResourceCreator<"provider", "register", (options?: APIClientProviderOptions) => (app: Jimpex) => void, _homer0_jimple.ProviderRegisterFn<Jimpex>>;
|
|
43
|
+
httpProvider: _homer0_jimple.Resource<"provider", "register", _homer0_jimple.ProviderRegisterFn<Jimpex>>;
|
|
44
|
+
responsesBuilderProvider: _homer0_jimple.Resource<"provider", "register", _homer0_jimple.ProviderRegisterFn<Jimpex>>;
|
|
45
|
+
} & Record<string, _homer0_jimple.Resource<"provider", "register", _homer0_jimple.ProviderRegisterFn<Jimpex>>> & {
|
|
46
|
+
provider: true;
|
|
47
|
+
} & {
|
|
48
|
+
register: _homer0_jimple.ProviderRegisterFn<Jimpex>;
|
|
49
|
+
} & Record<string, unknown>;
|
|
50
|
+
|
|
51
|
+
export { APIClientProviderOptions, httpServicesProvider };
|
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import * as _homer0_jimple from '@homer0/jimple';
|
|
2
|
-
import { J as Jimpex } from '../../
|
|
2
|
+
import { J as Jimpex } from '../../index-C6I3NCC-.js';
|
|
3
3
|
export { ErrorResponse } from '@homer0/api-utils';
|
|
4
4
|
import { APIClientProviderOptions } from './apiClient.js';
|
|
5
5
|
export { APIClient, APIClientConfig, APIClientConstructorOptions, APIClientSettings, EndpointsType, apiClientProvider } from './apiClient.js';
|
|
6
6
|
export { GetCustomHeadersFromRequestOptions, HTTP, HTTPContructorOptions, HTTPFetchBody, HTTPFetchOptions, HTTPOptions, httpProvider } from './http.js';
|
|
7
7
|
export { HTMLPostMessageResponseOptions, JSONResponseOptions, ResponsesBuilder, ResponsesBuilderConstructorOptions, responsesBuilderProvider } from './responsesBuilder.js';
|
|
8
|
-
import '@homer0/events-hub';
|
|
9
8
|
import '../../types/express.js';
|
|
10
9
|
import 'express';
|
|
11
10
|
import '../../types/http.js';
|
|
@@ -13,9 +12,11 @@ import 'https';
|
|
|
13
12
|
import 'http';
|
|
14
13
|
import 'spdy';
|
|
15
14
|
import 'node-fetch';
|
|
16
|
-
import '@homer0/simple-config';
|
|
17
15
|
import '../../types/utils.js';
|
|
16
|
+
import '@homer0/path-utils';
|
|
18
17
|
import '@homer0/simple-logger';
|
|
18
|
+
import '@homer0/simple-config';
|
|
19
|
+
import '@homer0/events-hub';
|
|
19
20
|
import '../common/httpError.js';
|
|
20
21
|
import '../../utils/fns/statuses.js';
|
|
21
22
|
import 'statuses';
|
|
@@ -36,6 +36,9 @@ const httpServicesProvider = (0, import_utils.providers)({
|
|
|
36
36
|
});
|
|
37
37
|
// Annotate the CommonJS export names for ESM import in node:
|
|
38
38
|
0 && (module.exports = {
|
|
39
|
-
httpServicesProvider
|
|
39
|
+
httpServicesProvider,
|
|
40
|
+
...require("./apiClient"),
|
|
41
|
+
...require("./http"),
|
|
42
|
+
...require("./responsesBuilder")
|
|
40
43
|
});
|
|
41
44
|
//# sourceMappingURL=index.js.map
|