@3sixty/api-core 0.0.0-stage → 0.20.0-next.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/LICENSE +201 -0
- package/README.md +24 -2
- package/dist/es/clients/baseRestClient.js +353 -0
- package/dist/es/clients/baseRestClient.js.map +1 -0
- package/dist/es/clients/baseSocketClient.js +112 -0
- package/dist/es/clients/baseSocketClient.js.map +1 -0
- package/dist/es/index.js +5 -0
- package/dist/es/index.js.map +1 -0
- package/dist/types/clients/baseRestClient.d.ts +36 -0
- package/dist/types/clients/baseSocketClient.d.ts +54 -0
- package/dist/types/index.d.ts +2 -0
- package/docs/changelog.md +0 -0
- package/docs/examples.md +109 -0
- package/docs/reference/classes/BaseRestClient.md +117 -0
- package/docs/reference/classes/BaseSocketClient.md +191 -0
- package/docs/reference/index.md +6 -0
- package/locales/en.json +9 -0
- package/package.json +52 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2024 IOTA Stiftung.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,25 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 3Sixty API Core
|
|
2
2
|
|
|
3
|
-
This
|
|
3
|
+
This package provides base client classes and common helpers for building HTTP and socket integrations.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```shell
|
|
8
|
+
npm install @3sixty/api-core
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
Usage of the APIs is shown in the examples [docs/examples.md](docs/examples.md)
|
|
14
|
+
|
|
15
|
+
## Reference
|
|
16
|
+
|
|
17
|
+
Detailed reference documentation for the API can be found in [docs/reference/index.md](docs/reference/index.md)
|
|
18
|
+
|
|
19
|
+
## Changelog
|
|
20
|
+
|
|
21
|
+
The changes between each version can be found in [docs/changelog.md](docs/changelog.md)
|
|
22
|
+
|
|
23
|
+
## Origin
|
|
24
|
+
|
|
25
|
+
This package is derived from the original [iotaledger/twin-api](https://github.com/iotaledger/twin-api/tree/next/packages/api-core) repository.
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
import { HttpUrlHelper, RestClientProcessorFactory } from "@3sixty/api-models";
|
|
2
|
+
import { BaseError, Coerce, Guards, Is, StringHelper } from "@3sixty/core";
|
|
3
|
+
import { FetchError, FetchHelper, HeaderTypes, HttpMethod, HttpStatusCode, MimeTypes } from "@3sixty/web";
|
|
4
|
+
/**
|
|
5
|
+
* Abstract client class for common REST processing.
|
|
6
|
+
*/
|
|
7
|
+
export class BaseRestClient {
|
|
8
|
+
/**
|
|
9
|
+
* The name of the class implementation REST calls.
|
|
10
|
+
* @internal
|
|
11
|
+
*/
|
|
12
|
+
_restClientClassName;
|
|
13
|
+
/**
|
|
14
|
+
* The endpoint origin without prefix.
|
|
15
|
+
* @internal
|
|
16
|
+
*/
|
|
17
|
+
_endpointOrigin;
|
|
18
|
+
/**
|
|
19
|
+
* The endpoint with prefix to send the requests to.
|
|
20
|
+
* @internal
|
|
21
|
+
*/
|
|
22
|
+
_endpointWithPrefix;
|
|
23
|
+
/**
|
|
24
|
+
* The path prefix without origin, e.g. "authentication/audit".
|
|
25
|
+
* @internal
|
|
26
|
+
*/
|
|
27
|
+
_pathPrefix;
|
|
28
|
+
/**
|
|
29
|
+
* Query parameters parsed from the configured endpoint URL. Preserved on every
|
|
30
|
+
* outbound request so that callers using endpoints like
|
|
31
|
+
* `https://host?tenant-token=…` don't lose routing data when the route+query are
|
|
32
|
+
* appended to the base URL.
|
|
33
|
+
* @internal
|
|
34
|
+
*/
|
|
35
|
+
_endpointQuery;
|
|
36
|
+
/**
|
|
37
|
+
* The headers to include in requests.
|
|
38
|
+
* @internal
|
|
39
|
+
*/
|
|
40
|
+
_headers;
|
|
41
|
+
/**
|
|
42
|
+
* Timeout for requests in ms.
|
|
43
|
+
* @internal
|
|
44
|
+
*/
|
|
45
|
+
_timeout;
|
|
46
|
+
/**
|
|
47
|
+
* Include credentials in the request, defaults to true.
|
|
48
|
+
* @internal
|
|
49
|
+
*/
|
|
50
|
+
_includeCredentials;
|
|
51
|
+
/**
|
|
52
|
+
* Hook to provide headers asynchronously.
|
|
53
|
+
* @internal
|
|
54
|
+
*/
|
|
55
|
+
_customHeaders;
|
|
56
|
+
/**
|
|
57
|
+
* Hook to provide auth header asynchronously.
|
|
58
|
+
* @internal
|
|
59
|
+
*/
|
|
60
|
+
_customAuthHeader;
|
|
61
|
+
/**
|
|
62
|
+
* The resolved processors.
|
|
63
|
+
* @internal
|
|
64
|
+
*/
|
|
65
|
+
_processors;
|
|
66
|
+
/**
|
|
67
|
+
* Hook to handle authorization failures asynchronously.
|
|
68
|
+
* @internal
|
|
69
|
+
*/
|
|
70
|
+
_onAuthFailure;
|
|
71
|
+
/**
|
|
72
|
+
* Create a new instance of BaseRestClient.
|
|
73
|
+
* @param restClientClassName The name of the class implementation REST calls.
|
|
74
|
+
* @param config The configuration for the client.
|
|
75
|
+
* @param pathPrefix The default prefix to use if none in configuration.
|
|
76
|
+
*/
|
|
77
|
+
constructor(restClientClassName, config, pathPrefix) {
|
|
78
|
+
Guards.stringValue(restClientClassName, "restClientClassName", restClientClassName);
|
|
79
|
+
Guards.object(restClientClassName, "config", config);
|
|
80
|
+
Guards.stringValue(restClientClassName, "config.endpoint", config.endpoint);
|
|
81
|
+
this._headers = config.headers;
|
|
82
|
+
this._timeout = config.timeout;
|
|
83
|
+
this._includeCredentials = config.includeCredentials ?? true;
|
|
84
|
+
this._restClientClassName = restClientClassName;
|
|
85
|
+
// Parse the endpoint as a URL so any query string the caller embedded is preserved
|
|
86
|
+
// rather than concatenated as part of the path.
|
|
87
|
+
this._endpointQuery = [];
|
|
88
|
+
let parsedEndpoint;
|
|
89
|
+
try {
|
|
90
|
+
parsedEndpoint = new URL(config.endpoint);
|
|
91
|
+
}
|
|
92
|
+
catch { }
|
|
93
|
+
if (Is.empty(parsedEndpoint)) {
|
|
94
|
+
this._endpointOrigin = StringHelper.trimTrailingSlashes(config.endpoint);
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
for (const [key, value] of parsedEndpoint.searchParams.entries()) {
|
|
98
|
+
this._endpointQuery.push({ key, value });
|
|
99
|
+
}
|
|
100
|
+
parsedEndpoint.search = "";
|
|
101
|
+
this._endpointOrigin = StringHelper.trimTrailingSlashes(parsedEndpoint.toString());
|
|
102
|
+
}
|
|
103
|
+
this._endpointWithPrefix = this._endpointOrigin;
|
|
104
|
+
const finalPathPrefix = config.pathPrefix ?? pathPrefix;
|
|
105
|
+
this._pathPrefix = Is.stringValue(finalPathPrefix) ? finalPathPrefix : "";
|
|
106
|
+
if (Is.stringValue(this._pathPrefix)) {
|
|
107
|
+
this._endpointWithPrefix += `/${this._pathPrefix}`;
|
|
108
|
+
}
|
|
109
|
+
this._customAuthHeader = config.customAuthHeader;
|
|
110
|
+
this._customHeaders = config.customHeaders;
|
|
111
|
+
this._onAuthFailure = config.onAuthFailure;
|
|
112
|
+
this._processors = (config.processorTypes ?? []).map(processorType => RestClientProcessorFactory.get(processorType));
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Get the endpoint with the prefix for the namespace.
|
|
116
|
+
* @returns The endpoint with namespace prefix attached.
|
|
117
|
+
*/
|
|
118
|
+
getEndpointWithPrefix() {
|
|
119
|
+
return this._endpointWithPrefix;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Get the path prefix as a URL path string provided in the constructor.
|
|
123
|
+
* @returns The path prefix.
|
|
124
|
+
*/
|
|
125
|
+
getPathPrefix() {
|
|
126
|
+
return this._pathPrefix;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Perform a request in json format.
|
|
130
|
+
* @param route The route of the request.
|
|
131
|
+
* @param method The http method.
|
|
132
|
+
* @param request Request to send to the endpoint.
|
|
133
|
+
* @param options Optional override options for the request.
|
|
134
|
+
* @param options.overridePrefix Optional override prefix to use for this request instead of the default prefix.
|
|
135
|
+
* @returns The response.
|
|
136
|
+
*/
|
|
137
|
+
async fetch(route, method, request, options) {
|
|
138
|
+
Guards.stringValue(this._restClientClassName, "route", route);
|
|
139
|
+
Guards.arrayOneOf(this._restClientClassName, "method", method, Object.values(HttpMethod));
|
|
140
|
+
const routeParts = route.split("/");
|
|
141
|
+
for (let i = 0; i < routeParts.length; i++) {
|
|
142
|
+
if (routeParts[i].startsWith(":")) {
|
|
143
|
+
const routeProp = routeParts[i].slice(1);
|
|
144
|
+
const pathValue = request?.pathParams?.[routeProp];
|
|
145
|
+
if (Is.notEmpty(pathValue)) {
|
|
146
|
+
routeParts[i] = Coerce.string(pathValue) ?? "";
|
|
147
|
+
delete request?.pathParams?.[routeProp];
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
throw new FetchError(this._restClientClassName, `${"baseRestClient"}.missingRouteProp`, HttpStatusCode.badRequest, { route, routeProp });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
// Preserve endpoint-level query params (parsed once in the constructor)
|
|
155
|
+
// alongside any per-request query params.
|
|
156
|
+
const queryKeyPairs = [...this._endpointQuery];
|
|
157
|
+
const isHttpRequest = Is.notEmpty(request);
|
|
158
|
+
if (isHttpRequest) {
|
|
159
|
+
const query = request?.query;
|
|
160
|
+
if (Is.object(query)) {
|
|
161
|
+
for (const qp in query) {
|
|
162
|
+
const propValue = query[qp];
|
|
163
|
+
if (Is.string(propValue) || Is.number(propValue) || Is.boolean(propValue)) {
|
|
164
|
+
const ids = queryKeyPairs.findIndex(q => q.key === qp);
|
|
165
|
+
if (ids !== -1) {
|
|
166
|
+
queryKeyPairs.splice(ids, 1);
|
|
167
|
+
}
|
|
168
|
+
queryKeyPairs.push({
|
|
169
|
+
key: qp,
|
|
170
|
+
value: propValue.toString()
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
delete request?.query;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
let finalRoute = routeParts.map(rp => HttpUrlHelper.encodeUriPathSegment(rp)).join("/");
|
|
178
|
+
if (finalRoute === "/") {
|
|
179
|
+
finalRoute = "";
|
|
180
|
+
}
|
|
181
|
+
if (queryKeyPairs.length > 0) {
|
|
182
|
+
finalRoute += `?${queryKeyPairs
|
|
183
|
+
.map(qp => `${encodeURIComponent(qp.key)}=${encodeURIComponent(qp.value)}`)
|
|
184
|
+
.join("&")}`;
|
|
185
|
+
}
|
|
186
|
+
const body = isHttpRequest && request?.body ? JSON.stringify(request?.body) : undefined;
|
|
187
|
+
let requestHeaders = {};
|
|
188
|
+
if (body) {
|
|
189
|
+
requestHeaders[HeaderTypes.ContentType] = MimeTypes.Json;
|
|
190
|
+
}
|
|
191
|
+
if (Is.object(this._headers)) {
|
|
192
|
+
requestHeaders = { ...requestHeaders, ...this._headers };
|
|
193
|
+
}
|
|
194
|
+
if (Is.object(request?.headers)) {
|
|
195
|
+
requestHeaders = { ...requestHeaders, ...request.headers };
|
|
196
|
+
}
|
|
197
|
+
if (Is.function(this._customHeaders)) {
|
|
198
|
+
const customHeaders = await this._customHeaders();
|
|
199
|
+
if (Is.object(customHeaders)) {
|
|
200
|
+
requestHeaders = { ...requestHeaders, ...customHeaders };
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (Is.function(this._customAuthHeader)) {
|
|
204
|
+
const authHeader = await this._customAuthHeader();
|
|
205
|
+
if (Is.stringValue(authHeader)) {
|
|
206
|
+
requestHeaders[HeaderTypes.Authorization] = authHeader;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
let baseUrl;
|
|
210
|
+
if (Is.string(options?.overridePrefix)) {
|
|
211
|
+
baseUrl =
|
|
212
|
+
options.overridePrefix.length > 0
|
|
213
|
+
? `${this._endpointOrigin}/${options.overridePrefix}`
|
|
214
|
+
: this._endpointOrigin;
|
|
215
|
+
}
|
|
216
|
+
else {
|
|
217
|
+
baseUrl = this._endpointWithPrefix;
|
|
218
|
+
}
|
|
219
|
+
const context = {
|
|
220
|
+
restClientClassName: this._restClientClassName,
|
|
221
|
+
baseUrl,
|
|
222
|
+
routeTemplate: route,
|
|
223
|
+
route: finalRoute,
|
|
224
|
+
method,
|
|
225
|
+
headers: requestHeaders,
|
|
226
|
+
timeout: this._timeout,
|
|
227
|
+
includeCredentials: this._includeCredentials,
|
|
228
|
+
body
|
|
229
|
+
};
|
|
230
|
+
const rawResponse = await this.runProcessorsPre(context, async () => FetchHelper.fetch(this._restClientClassName, `${context.baseUrl}${context.route}`, context.method, context.body, {
|
|
231
|
+
headers: context.headers,
|
|
232
|
+
timeoutMs: context.timeout,
|
|
233
|
+
includeCredentials: context.includeCredentials
|
|
234
|
+
}));
|
|
235
|
+
const response = await this.runProcessorsPost(context, rawResponse);
|
|
236
|
+
if (response.ok) {
|
|
237
|
+
try {
|
|
238
|
+
const httpResponse = {};
|
|
239
|
+
const contentType = response.headers.get(HeaderTypes.ContentType) ??
|
|
240
|
+
response.headers.get(HeaderTypes.ContentType.toLowerCase()) ??
|
|
241
|
+
"";
|
|
242
|
+
if (response.status !== HttpStatusCode.noContent) {
|
|
243
|
+
if (contentType.includes(MimeTypes.PlainText)) {
|
|
244
|
+
httpResponse.body = await response.text();
|
|
245
|
+
}
|
|
246
|
+
else if (contentType.includes(MimeTypes.Json) ||
|
|
247
|
+
contentType.includes(MimeTypes.JsonLd)) {
|
|
248
|
+
httpResponse.body = await response.json();
|
|
249
|
+
}
|
|
250
|
+
else {
|
|
251
|
+
httpResponse.body = new Uint8Array(await response.arrayBuffer());
|
|
252
|
+
if (httpResponse.body.length === 0) {
|
|
253
|
+
delete httpResponse.body;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const responseHeaders = {};
|
|
258
|
+
for (const header of response.headers.entries()) {
|
|
259
|
+
responseHeaders[header[0]] = header[1];
|
|
260
|
+
}
|
|
261
|
+
if (Object.keys(responseHeaders).length > 0) {
|
|
262
|
+
httpResponse.headers = responseHeaders;
|
|
263
|
+
}
|
|
264
|
+
if (response.status !== HttpStatusCode.ok) {
|
|
265
|
+
httpResponse.statusCode = response.status;
|
|
266
|
+
}
|
|
267
|
+
return httpResponse;
|
|
268
|
+
}
|
|
269
|
+
catch (err) {
|
|
270
|
+
throw new FetchError(this._restClientClassName, `${"baseRestClient"}.decodingFailed`, response.status, {
|
|
271
|
+
route
|
|
272
|
+
}, err);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
const errResponse = await response.json();
|
|
276
|
+
let err;
|
|
277
|
+
if (response.status >= HttpStatusCode.badRequest &&
|
|
278
|
+
Is.object(errResponse) &&
|
|
279
|
+
Is.stringValue(errResponse.message)) {
|
|
280
|
+
err = BaseError.fromError(errResponse);
|
|
281
|
+
}
|
|
282
|
+
err ??= new FetchError(this._restClientClassName, `${"baseRestClient"}.failureStatusText`, response.status, {
|
|
283
|
+
statusText: response.statusText ?? response.status,
|
|
284
|
+
route: finalRoute,
|
|
285
|
+
response: errResponse
|
|
286
|
+
});
|
|
287
|
+
if (response.status === HttpStatusCode.unauthorized && Is.function(this._onAuthFailure)) {
|
|
288
|
+
try {
|
|
289
|
+
await this._onAuthFailure(err);
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
// Silently ignore errors from the auth failure handler as we want to throw the original error
|
|
293
|
+
// in this case to preserve the original failure context for logging and handling by callers
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
throw err;
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Run the pre operation for any processors.
|
|
300
|
+
* @param context The processor context.
|
|
301
|
+
* @param perform Performs the request.
|
|
302
|
+
* @returns The response.
|
|
303
|
+
* @internal
|
|
304
|
+
*/
|
|
305
|
+
async runProcessorsPre(context, perform) {
|
|
306
|
+
if (this._processors.length === 0) {
|
|
307
|
+
return perform();
|
|
308
|
+
}
|
|
309
|
+
// Built from the last processor backwards.
|
|
310
|
+
// For ["a", "b"] that gives a.pre -> b.pre -> perform.
|
|
311
|
+
let next = perform;
|
|
312
|
+
for (let i = this._processors.length - 1; i >= 0; i--) {
|
|
313
|
+
const processor = this._processors[i];
|
|
314
|
+
const inner = next;
|
|
315
|
+
const preFuncBound = processor.pre?.bind(processor);
|
|
316
|
+
if (Is.function(preFuncBound)) {
|
|
317
|
+
next = async () => preFuncBound(context, inner);
|
|
318
|
+
}
|
|
319
|
+
else {
|
|
320
|
+
next = inner;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return next();
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Run the post operation for any processors.
|
|
327
|
+
* @param context The processor context.
|
|
328
|
+
* @param response The response from the fetch.
|
|
329
|
+
* @returns The response.
|
|
330
|
+
* @internal
|
|
331
|
+
*/
|
|
332
|
+
async runProcessorsPost(context, response) {
|
|
333
|
+
if (this._processors.length === 0) {
|
|
334
|
+
return response;
|
|
335
|
+
}
|
|
336
|
+
// Built from first to last so that the last processor is outermost.
|
|
337
|
+
// For ["a", "b"] that gives b.post -> a.post -> response (reverse of pre).
|
|
338
|
+
let next = async () => response;
|
|
339
|
+
for (let i = 0; i < this._processors.length; i++) {
|
|
340
|
+
const processor = this._processors[i];
|
|
341
|
+
const inner = next;
|
|
342
|
+
const postFuncBound = processor.post?.bind(processor);
|
|
343
|
+
if (Is.function(postFuncBound)) {
|
|
344
|
+
next = async () => postFuncBound(context, response, inner);
|
|
345
|
+
}
|
|
346
|
+
else {
|
|
347
|
+
next = inner;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
return next();
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
//# sourceMappingURL=baseRestClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"baseRestClient.js","sourceRoot":"","sources":["../../../src/clients/baseRestClient.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,aAAa,EAAE,0BAA0B,EAAE,MAAM,oBAAoB,CAAC;AAC/E,OAAO,EACN,SAAS,EACT,MAAM,EACN,MAAM,EAEN,EAAE,EACF,YAAY,EAEZ,MAAM,cAAc,CAAC;AAEtB,OAAO,EACN,UAAU,EACV,WAAW,EACX,WAAW,EACX,UAAU,EACV,cAAc,EACd,SAAS,EAET,MAAM,aAAa,CAAC;AAErB;;GAEG;AACH,MAAM,OAAgB,cAAc;IACnC;;;OAGG;IACc,oBAAoB,CAAS;IAE9C;;;OAGG;IACc,eAAe,CAAS;IAEzC;;;OAGG;IACc,mBAAmB,CAAS;IAE7C;;;OAGG;IACc,WAAW,CAAS;IAErC;;;;;;OAMG;IACc,cAAc,CAAsB;IAErD;;;OAGG;IACc,QAAQ,CAAgB;IAEzC;;;OAGG;IACc,QAAQ,CAAU;IAEnC;;;OAGG;IACc,mBAAmB,CAAU;IAE9C;;;OAGG;IACc,cAAc,CAA+B;IAE9D;;;OAGG;IACc,iBAAiB,CAAyB;IAE3D;;;OAGG;IACc,WAAW,CAAyB;IAErD;;;OAGG;IACc,cAAc,CAAoC;IAEnE;;;;;OAKG;IACH,YAAY,mBAA2B,EAAE,MAA6B,EAAE,UAAkB;QACzF,MAAM,CAAC,WAAW,CAAC,mBAAmB,yBAA+B,mBAAmB,CAAC,CAAC;QAC1F,MAAM,CAAC,MAAM,CAAwB,mBAAmB,YAAkB,MAAM,CAAC,CAAC;QAClF,MAAM,CAAC,WAAW,CAAC,mBAAmB,qBAA2B,MAAM,CAAC,QAAQ,CAAC,CAAC;QAElF,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC;QAC/B,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC;QAC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,EAAE,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,CAAC;gBAC/B,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC,YAAY,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;YACjD,CAAC;iBAAM,CAAC;gBACP,IAAI,GAAG,KAAK,CAAC;YACd,CAAC;QACF,CAAC;QAED,OAAO,IAAI,EAAE,CAAC;IACf,CAAC;IAED;;;;;;OAMG;IACK,KAAK,CAAC,iBAAiB,CAC9B,OAAoC,EACpC,QAAkB;QAElB,IAAI,IAAI,CAAC,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACnC,OAAO,QAAQ,CAAC;QACjB,CAAC;QAED,oEAAoE;QACpE,2EAA2E;QAC3E,IAAI,IAAI,GAAG,KAAK,IAAuB,EAAE,CAAC,QAAQ,CAAC;QACnD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAClD,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;YACtC,MAAM,KAAK,GAAG,IAAI,CAAC;YACnB,MAAM,aAAa,GAAG,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;YACtD,IAAI,EAAE,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAC;gBAChC,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC,aAAa,CAAC,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;YAC5D,CAAC;iBAAM,CAAC;gBACP,IAAI,GAAG,KAAK,CAAC;YACd,CAAC;QACF,CAAC;QAED,OAAO,IAAI,EAAE,CAAC;IACf,CAAC;CACD","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type {\n\tIBaseRestClientConfig,\n\tIHttpRequest,\n\tIHttpResponse,\n\tIRestClientProcessor,\n\tIRestClientProcessorContext\n} from \"@3sixty/api-models\";\nimport { HttpUrlHelper, RestClientProcessorFactory } from \"@3sixty/api-models\";\nimport {\n\tBaseError,\n\tCoerce,\n\tGuards,\n\ttype IError,\n\tIs,\n\tStringHelper,\n\ttype IKeyValue\n} from \"@3sixty/core\";\nimport { nameof, nameofCamelCase } from \"@3sixty/nameof\";\nimport {\n\tFetchError,\n\tFetchHelper,\n\tHeaderTypes,\n\tHttpMethod,\n\tHttpStatusCode,\n\tMimeTypes,\n\ttype IHttpHeaders\n} from \"@3sixty/web\";\n\n/**\n * Abstract client class for common REST processing.\n */\nexport abstract class BaseRestClient {\n\t/**\n\t * The name of the class implementation REST calls.\n\t * @internal\n\t */\n\tprivate readonly _restClientClassName: string;\n\n\t/**\n\t * The endpoint origin without prefix.\n\t * @internal\n\t */\n\tprivate readonly _endpointOrigin: string;\n\n\t/**\n\t * The endpoint with prefix to send the requests to.\n\t * @internal\n\t */\n\tprivate readonly _endpointWithPrefix: string;\n\n\t/**\n\t * The path prefix without origin, e.g. \"authentication/audit\".\n\t * @internal\n\t */\n\tprivate readonly _pathPrefix: string;\n\n\t/**\n\t * Query parameters parsed from the configured endpoint URL. Preserved on every\n\t * outbound request so that callers using endpoints like\n\t * `https://host?tenant-token=…` don't lose routing data when the route+query are\n\t * appended to the base URL.\n\t * @internal\n\t */\n\tprivate readonly _endpointQuery: IKeyValue<string>[];\n\n\t/**\n\t * The headers to include in requests.\n\t * @internal\n\t */\n\tprivate readonly _headers?: IHttpHeaders;\n\n\t/**\n\t * Timeout for requests in ms.\n\t * @internal\n\t */\n\tprivate readonly _timeout?: number;\n\n\t/**\n\t * Include credentials in the request, defaults to true.\n\t * @internal\n\t */\n\tprivate readonly _includeCredentials: boolean;\n\n\t/**\n\t * Hook to provide headers asynchronously.\n\t * @internal\n\t */\n\tprivate readonly _customHeaders?: () => Promise<IHttpHeaders>;\n\n\t/**\n\t * Hook to provide auth header asynchronously.\n\t * @internal\n\t */\n\tprivate readonly _customAuthHeader?: () => Promise<string>;\n\n\t/**\n\t * The resolved processors.\n\t * @internal\n\t */\n\tprivate readonly _processors: IRestClientProcessor[];\n\n\t/**\n\t * Hook to handle authorization failures asynchronously.\n\t * @internal\n\t */\n\tprivate readonly _onAuthFailure?: (error: IError) => Promise<void>;\n\n\t/**\n\t * Create a new instance of BaseRestClient.\n\t * @param restClientClassName The name of the class implementation REST calls.\n\t * @param config The configuration for the client.\n\t * @param pathPrefix The default prefix to use if none in configuration.\n\t */\n\tconstructor(restClientClassName: string, config: IBaseRestClientConfig, pathPrefix: string) {\n\t\tGuards.stringValue(restClientClassName, nameof(restClientClassName), restClientClassName);\n\t\tGuards.object<IBaseRestClientConfig>(restClientClassName, nameof(config), config);\n\t\tGuards.stringValue(restClientClassName, nameof(config.endpoint), config.endpoint);\n\n\t\tthis._headers = config.headers;\n\t\tthis._timeout = config.timeout;\n\t\tthis._includeCredentials = config.includeCredentials ?? true;\n\n\t\tthis._restClientClassName = restClientClassName;\n\n\t\t// Parse the endpoint as a URL so any query string the caller embedded is preserved\n\t\t// rather than concatenated as part of the path.\n\t\tthis._endpointQuery = [];\n\t\tlet parsedEndpoint: URL | undefined;\n\t\ttry {\n\t\t\tparsedEndpoint = new URL(config.endpoint);\n\t\t} catch {}\n\n\t\tif (Is.empty(parsedEndpoint)) {\n\t\t\tthis._endpointOrigin = StringHelper.trimTrailingSlashes(config.endpoint);\n\t\t} else {\n\t\t\tfor (const [key, value] of parsedEndpoint.searchParams.entries()) {\n\t\t\t\tthis._endpointQuery.push({ key, value });\n\t\t\t}\n\t\t\tparsedEndpoint.search = \"\";\n\t\t\tthis._endpointOrigin = StringHelper.trimTrailingSlashes(parsedEndpoint.toString());\n\t\t}\n\n\t\tthis._endpointWithPrefix = this._endpointOrigin;\n\t\tconst finalPathPrefix = config.pathPrefix ?? pathPrefix;\n\t\tthis._pathPrefix = Is.stringValue(finalPathPrefix) ? finalPathPrefix : \"\";\n\t\tif (Is.stringValue(this._pathPrefix)) {\n\t\t\tthis._endpointWithPrefix += `/${this._pathPrefix}`;\n\t\t}\n\n\t\tthis._customAuthHeader = config.customAuthHeader;\n\t\tthis._customHeaders = config.customHeaders;\n\t\tthis._onAuthFailure = config.onAuthFailure;\n\t\tthis._processors = (config.processorTypes ?? []).map(processorType =>\n\t\t\tRestClientProcessorFactory.get(processorType)\n\t\t);\n\t}\n\n\t/**\n\t * Get the endpoint with the prefix for the namespace.\n\t * @returns The endpoint with namespace prefix attached.\n\t */\n\tpublic getEndpointWithPrefix(): string {\n\t\treturn this._endpointWithPrefix;\n\t}\n\n\t/**\n\t * Get the path prefix as a URL path string provided in the constructor.\n\t * @returns The path prefix.\n\t */\n\tpublic getPathPrefix(): string {\n\t\treturn this._pathPrefix;\n\t}\n\n\t/**\n\t * Perform a request in json format.\n\t * @param route The route of the request.\n\t * @param method The http method.\n\t * @param request Request to send to the endpoint.\n\t * @param options Optional override options for the request.\n\t * @param options.overridePrefix Optional override prefix to use for this request instead of the default prefix.\n\t * @returns The response.\n\t */\n\tpublic async fetch<T extends IHttpRequest, U extends IHttpResponse>(\n\t\troute: string,\n\t\tmethod: HttpMethod,\n\t\trequest?: T,\n\t\toptions?: { overridePrefix?: string }\n\t): Promise<U> {\n\t\tGuards.stringValue(this._restClientClassName, nameof(route), route);\n\t\tGuards.arrayOneOf(this._restClientClassName, nameof(method), method, Object.values(HttpMethod));\n\n\t\tconst routeParts = route.split(\"/\");\n\n\t\tfor (let i = 0; i < routeParts.length; i++) {\n\t\t\tif (routeParts[i].startsWith(\":\")) {\n\t\t\t\tconst routeProp = routeParts[i].slice(1);\n\t\t\t\tconst pathValue = request?.pathParams?.[routeProp];\n\t\t\t\tif (Is.notEmpty(pathValue)) {\n\t\t\t\t\trouteParts[i] = Coerce.string(pathValue) ?? \"\";\n\t\t\t\t\tdelete request?.pathParams?.[routeProp];\n\t\t\t\t} else {\n\t\t\t\t\tthrow new FetchError(\n\t\t\t\t\t\tthis._restClientClassName,\n\t\t\t\t\t\t`${nameofCamelCase<BaseRestClient>()}.missingRouteProp`,\n\t\t\t\t\t\tHttpStatusCode.badRequest,\n\t\t\t\t\t\t{ route, routeProp }\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Preserve endpoint-level query params (parsed once in the constructor)\n\t\t// alongside any per-request query params.\n\t\tconst queryKeyPairs: IKeyValue<string>[] = [...this._endpointQuery];\n\n\t\tconst isHttpRequest = Is.notEmpty(request);\n\n\t\tif (isHttpRequest) {\n\t\t\tconst query = request?.query;\n\t\t\tif (Is.object(query)) {\n\t\t\t\tfor (const qp in query) {\n\t\t\t\t\tconst propValue = query[qp];\n\t\t\t\t\tif (Is.string(propValue) || Is.number(propValue) || Is.boolean(propValue)) {\n\t\t\t\t\t\tconst ids = queryKeyPairs.findIndex(q => q.key === qp);\n\t\t\t\t\t\tif (ids !== -1) {\n\t\t\t\t\t\t\tqueryKeyPairs.splice(ids, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tqueryKeyPairs.push({\n\t\t\t\t\t\t\tkey: qp,\n\t\t\t\t\t\t\tvalue: propValue.toString()\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdelete request?.query;\n\t\t\t}\n\t\t}\n\n\t\tlet finalRoute = routeParts.map(rp => HttpUrlHelper.encodeUriPathSegment(rp)).join(\"/\");\n\t\tif (finalRoute === \"/\") {\n\t\t\tfinalRoute = \"\";\n\t\t}\n\t\tif (queryKeyPairs.length > 0) {\n\t\t\tfinalRoute += `?${queryKeyPairs\n\t\t\t\t.map(qp => `${encodeURIComponent(qp.key)}=${encodeURIComponent(qp.value)}`)\n\t\t\t\t.join(\"&\")}`;\n\t\t}\n\n\t\tconst body = isHttpRequest && request?.body ? JSON.stringify(request?.body) : undefined;\n\n\t\tlet requestHeaders: IHttpHeaders = {};\n\n\t\tif (body) {\n\t\t\trequestHeaders[HeaderTypes.ContentType] = MimeTypes.Json;\n\t\t}\n\n\t\tif (Is.object(this._headers)) {\n\t\t\trequestHeaders = { ...requestHeaders, ...this._headers };\n\t\t}\n\n\t\tif (Is.object(request?.headers)) {\n\t\t\trequestHeaders = { ...requestHeaders, ...request.headers };\n\t\t}\n\n\t\tif (Is.function(this._customHeaders)) {\n\t\t\tconst customHeaders = await this._customHeaders();\n\t\t\tif (Is.object(customHeaders)) {\n\t\t\t\trequestHeaders = { ...requestHeaders, ...customHeaders };\n\t\t\t}\n\t\t}\n\n\t\tif (Is.function(this._customAuthHeader)) {\n\t\t\tconst authHeader = await this._customAuthHeader();\n\t\t\tif (Is.stringValue(authHeader)) {\n\t\t\t\trequestHeaders[HeaderTypes.Authorization] = authHeader;\n\t\t\t}\n\t\t}\n\n\t\tlet baseUrl;\n\n\t\tif (Is.string(options?.overridePrefix)) {\n\t\t\tbaseUrl =\n\t\t\t\toptions.overridePrefix.length > 0\n\t\t\t\t\t? `${this._endpointOrigin}/${options.overridePrefix}`\n\t\t\t\t\t: this._endpointOrigin;\n\t\t} else {\n\t\t\tbaseUrl = this._endpointWithPrefix;\n\t\t}\n\n\t\tconst context: IRestClientProcessorContext = {\n\t\t\trestClientClassName: this._restClientClassName,\n\t\t\tbaseUrl,\n\t\t\trouteTemplate: route,\n\t\t\troute: finalRoute,\n\t\t\tmethod,\n\t\t\theaders: requestHeaders,\n\t\t\ttimeout: this._timeout,\n\t\t\tincludeCredentials: this._includeCredentials,\n\t\t\tbody\n\t\t};\n\n\t\tconst rawResponse = await this.runProcessorsPre(context, async () =>\n\t\t\tFetchHelper.fetch(\n\t\t\t\tthis._restClientClassName,\n\t\t\t\t`${context.baseUrl}${context.route}`,\n\t\t\t\tcontext.method,\n\t\t\t\tcontext.body,\n\t\t\t\t{\n\t\t\t\t\theaders: context.headers,\n\t\t\t\t\ttimeoutMs: context.timeout,\n\t\t\t\t\tincludeCredentials: context.includeCredentials\n\t\t\t\t}\n\t\t\t)\n\t\t);\n\n\t\tconst response = await this.runProcessorsPost(context, rawResponse);\n\n\t\tif (response.ok) {\n\t\t\ttry {\n\t\t\t\tconst httpResponse: IHttpResponse = {};\n\n\t\t\t\tconst contentType =\n\t\t\t\t\tresponse.headers.get(HeaderTypes.ContentType) ??\n\t\t\t\t\tresponse.headers.get(HeaderTypes.ContentType.toLowerCase()) ??\n\t\t\t\t\t\"\";\n\n\t\t\t\tif (response.status !== HttpStatusCode.noContent) {\n\t\t\t\t\tif (contentType.includes(MimeTypes.PlainText)) {\n\t\t\t\t\t\thttpResponse.body = await response.text();\n\t\t\t\t\t} else if (\n\t\t\t\t\t\tcontentType.includes(MimeTypes.Json) ||\n\t\t\t\t\t\tcontentType.includes(MimeTypes.JsonLd)\n\t\t\t\t\t) {\n\t\t\t\t\t\thttpResponse.body = await response.json();\n\t\t\t\t\t} else {\n\t\t\t\t\t\thttpResponse.body = new Uint8Array(await response.arrayBuffer());\n\t\t\t\t\t\tif (httpResponse.body.length === 0) {\n\t\t\t\t\t\t\tdelete httpResponse.body;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst responseHeaders: IHttpHeaders = {};\n\t\t\t\tfor (const header of response.headers.entries()) {\n\t\t\t\t\tresponseHeaders[header[0]] = header[1];\n\t\t\t\t}\n\n\t\t\t\tif (Object.keys(responseHeaders).length > 0) {\n\t\t\t\t\thttpResponse.headers = responseHeaders;\n\t\t\t\t}\n\n\t\t\t\tif (response.status !== HttpStatusCode.ok) {\n\t\t\t\t\thttpResponse.statusCode = response.status as HttpStatusCode;\n\t\t\t\t}\n\n\t\t\t\treturn httpResponse as U;\n\t\t\t} catch (err) {\n\t\t\t\tthrow new FetchError(\n\t\t\t\t\tthis._restClientClassName,\n\t\t\t\t\t`${nameofCamelCase<BaseRestClient>()}.decodingFailed`,\n\t\t\t\t\tresponse.status as HttpStatusCode,\n\t\t\t\t\t{\n\t\t\t\t\t\troute\n\t\t\t\t\t},\n\t\t\t\t\terr\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst errResponse = await response.json();\n\t\tlet err: BaseError | undefined;\n\t\tif (\n\t\t\tresponse.status >= HttpStatusCode.badRequest &&\n\t\t\tIs.object(errResponse) &&\n\t\t\tIs.stringValue(errResponse.message)\n\t\t) {\n\t\t\terr = BaseError.fromError(errResponse);\n\t\t}\n\n\t\terr ??= new FetchError(\n\t\t\tthis._restClientClassName,\n\t\t\t`${nameofCamelCase<BaseRestClient>()}.failureStatusText`,\n\t\t\tresponse.status as HttpStatusCode,\n\t\t\t{\n\t\t\t\tstatusText: response.statusText ?? response.status,\n\t\t\t\troute: finalRoute,\n\t\t\t\tresponse: errResponse\n\t\t\t}\n\t\t);\n\n\t\tif (response.status === HttpStatusCode.unauthorized && Is.function(this._onAuthFailure)) {\n\t\t\ttry {\n\t\t\t\tawait this._onAuthFailure(err);\n\t\t\t} catch {\n\t\t\t\t// Silently ignore errors from the auth failure handler as we want to throw the original error\n\t\t\t\t// in this case to preserve the original failure context for logging and handling by callers\n\t\t\t}\n\t\t}\n\n\t\tthrow err;\n\t}\n\n\t/**\n\t * Run the pre operation for any processors.\n\t * @param context The processor context.\n\t * @param perform Performs the request.\n\t * @returns The response.\n\t * @internal\n\t */\n\tprivate async runProcessorsPre(\n\t\tcontext: IRestClientProcessorContext,\n\t\tperform: () => Promise<Response>\n\t): Promise<Response> {\n\t\tif (this._processors.length === 0) {\n\t\t\treturn perform();\n\t\t}\n\n\t\t// Built from the last processor backwards.\n\t\t// For [\"a\", \"b\"] that gives a.pre -> b.pre -> perform.\n\t\tlet next = perform;\n\t\tfor (let i = this._processors.length - 1; i >= 0; i--) {\n\t\t\tconst processor = this._processors[i];\n\t\t\tconst inner = next;\n\t\t\tconst preFuncBound = processor.pre?.bind(processor);\n\t\t\tif (Is.function(preFuncBound)) {\n\t\t\t\tnext = async () => preFuncBound(context, inner);\n\t\t\t} else {\n\t\t\t\tnext = inner;\n\t\t\t}\n\t\t}\n\n\t\treturn next();\n\t}\n\n\t/**\n\t * Run the post operation for any processors.\n\t * @param context The processor context.\n\t * @param response The response from the fetch.\n\t * @returns The response.\n\t * @internal\n\t */\n\tprivate async runProcessorsPost(\n\t\tcontext: IRestClientProcessorContext,\n\t\tresponse: Response\n\t): Promise<Response> {\n\t\tif (this._processors.length === 0) {\n\t\t\treturn response;\n\t\t}\n\n\t\t// Built from first to last so that the last processor is outermost.\n\t\t// For [\"a\", \"b\"] that gives b.post -> a.post -> response (reverse of pre).\n\t\tlet next = async (): Promise<Response> => response;\n\t\tfor (let i = 0; i < this._processors.length; i++) {\n\t\t\tconst processor = this._processors[i];\n\t\t\tconst inner = next;\n\t\t\tconst postFuncBound = processor.post?.bind(processor);\n\t\t\tif (Is.function(postFuncBound)) {\n\t\t\t\tnext = async () => postFuncBound(context, response, inner);\n\t\t\t} else {\n\t\t\t\tnext = inner;\n\t\t\t}\n\t\t}\n\n\t\treturn next();\n\t}\n}\n"]}
|