-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathDefaultRESTClient.ts
271 lines (242 loc) · 7.66 KB
/
DefaultRESTClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
/*
* Copyright (c) 2019-2024, FusionAuth, All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
import IRESTClient, { ErrorResponseHandler, ResponseHandler } from "./IRESTClient";
import ClientResponse from "./ClientResponse";
import fetch, { BodyInit, RequestCredentials, Response } from "node-fetch";
import { URLSearchParams } from "url";
/**
* @author Brett P
* @author Tyler Scott
* @author TJ Peden
*/
export default class DefaultRESTClient<RT, ERT> implements IRESTClient<RT, ERT> {
public body: BodyInit;
public headers: Record<string, string> = {};
public method: string;
public parameters: Record<string, string> = {};
public uri: string;
public credentials: RequestCredentials;
public responseHandler: ResponseHandler<RT> = DefaultRESTClient.JSONResponseHandler;
public errorResponseHandler: ErrorResponseHandler<ERT> = DefaultRESTClient.ErrorJSONResponseHandler;
public abortSignal: AbortSignal = undefined;
constructor(public host: string) {
}
/**
* A function that returns the JSON form of the response text.
*
* @param response
* @constructor
*/
static async JSONResponseHandler<RT>(response: Response): Promise<ClientResponse<RT>> {
let clientResponse = new ClientResponse<RT>();
clientResponse.statusCode = response.status;
let type = response.headers.get("content-type");
if (type && type.startsWith("application/json")) {
clientResponse.response = await response.json();
}
return clientResponse;
}
/**
* A function that returns the JSON form of the response text.
*
* @param response
* @constructor
*/
static async ErrorJSONResponseHandler<ERT>(response: Response): Promise<ClientResponse<ERT>> {
let clientResponse = new ClientResponse<ERT>();
clientResponse.statusCode = response.status;
let type = response.headers.get("content-type");
if (type && type.startsWith("application/json")) {
clientResponse.exception = await response.json();
}
return clientResponse;
}
/**
* Sets the authorization header using a key
*
* @param {string} key The value of the authorization header.
* @returns {DefaultRESTClient}
*/
withAuthorization(key: string): DefaultRESTClient<RT, ERT> {
if (key === null || typeof key === 'undefined') {
return this;
}
this.withHeader('Authorization', key);
return this;
}
/**
* Adds a segment to the request uri
*/
withUriSegment(segment: string | number): DefaultRESTClient<RT, ERT> {
if (segment === null || segment === undefined) {
return this;
}
if (this.uri === null) {
this.uri = '';
}
if (this.uri.charAt(this.uri.length - 1) !== '/') {
this.uri += '/';
}
this.uri = this.uri + segment;
return this;
}
/**
* Get the full url + parameter list
*/
getFullUrl() {
return this.host + this.uri + this.getQueryString();
}
/**
* Sets the body of the client request.
*
* @param body The object to be written to the request body as form data.
*/
withFormData(body: URLSearchParams): DefaultRESTClient<RT, ERT> {
const body2 = new URLSearchParams();
if (body) {
body.forEach((value, name, searchParams) => {
if (value && value.length > 0 && value != "null" && value != "undefined") {
body2.set(name, value);
}
});
body = body2;
}
this.body = body;
this.withHeader('Content-Type', 'application/x-www-form-urlencoded');
return this;
}
/**
* Adds a header to the request.
*
* @param key The name of the header.
* @param value The value of the header.
*/
withHeader(key: string, value: string): DefaultRESTClient<RT, ERT> {
this.headers[key] = value;
return this;
}
/**
* Sets the body of the client request.
*
* @param body The object to be written to the request body as JSON.
*/
withJSONBody(body: object): DefaultRESTClient<RT, ERT> {
this.body = JSON.stringify(body);
this.withHeader('Content-Type', 'application/json');
// Omit the Content-Length, this is set auto-magically by the request library
return this;
}
/**
* Sets the http method for the request
*/
withMethod(method: string): DefaultRESTClient<RT, ERT> {
this.method = method;
return this;
}
/**
* Sets the uri of the request
*/
withUri(uri: string): DefaultRESTClient<RT, ERT> {
this.uri = uri;
return this;
}
/**
* Adds parameters to the request.
*
* @param name The name of the parameter.
* @param value The value of the parameter, may be a string, object or number.
*/
withParameter(name: string, value: any): DefaultRESTClient<RT, ERT> {
this.parameters[name] = value;
return this;
}
/**
* Sets request's credentials.
*
* @param value A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL.
*/
withCredentials(value: RequestCredentials): DefaultRESTClient<RT, ERT> {
this.credentials = value;
return this;
}
withResponseHandler(handler: ResponseHandler<RT>): DefaultRESTClient<RT, ERT> {
this.responseHandler = handler;
return this;
}
withErrorResponseHandler(handler: ErrorResponseHandler<ERT>): DefaultRESTClient<RT, ERT> {
this.errorResponseHandler = handler;
return this;
}
/**
* Sets the AbortSignal for the request.
* @param signal The AbortSignal to use to abort the request.
*/
withAbortSignal(signal: AbortSignal): DefaultRESTClient<RT, ERT> {
this.abortSignal = signal;
return this;
}
/**
* Run the request and return a promise. This promise will resolve if the request is successful
* and reject otherwise.
*/
async go(): Promise<ClientResponse<RT>> {
const clientResponse = new ClientResponse<RT>();
let response: Response;
try {
response = await fetch(
this.getFullUrl(),
{
method: this.method,
headers: this.headers,
body: this.body as BodyInit,
// @ts-ignore (Credentials are not supported on NodeJS)
credentials: this.credentials,
signal: this.abortSignal,
},
);
if (response.ok) {
return await this.responseHandler(response);
} else {
throw await this.errorResponseHandler(response);
}
} catch (error) {
if (error instanceof ClientResponse) {
throw error; // Don't catch a ClientResponse (we want this to trigger the catch of the promise
}
if (response) { // Try to recover the response status
clientResponse.statusCode = response.status;
}
clientResponse.exception = error;
throw clientResponse;
}
}
private getQueryString() {
let queryString = '';
const appendParam = (key: string, param: string) => {
queryString += (queryString.length === 0) ? '?' : '&';
queryString += encodeURIComponent(key) + '=' + encodeURIComponent(param);
}
for (let key in this.parameters) {
const value = this.parameters[key];
if (Array.isArray(value)) {
value.forEach(val => appendParam(key, val))
} else {
appendParam(key, value);
}
}
return queryString;
}
}