-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathhttp-requests.ts
290 lines (245 loc) · 7.83 KB
/
http-requests.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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import type {
Config,
HttpRequestsRequestInit,
RequestOptions,
MainRequestOptions,
URLSearchParamsRecord,
MeiliSearchErrorResponse,
} from "./types/index.js";
import { PACKAGE_VERSION } from "./package-version.js";
import {
MeiliSearchError,
MeiliSearchApiError,
MeiliSearchRequestError,
MeiliSearchRequestTimeOutError,
} from "./errors/index.js";
import { addProtocolIfNotPresent, addTrailingSlash } from "./utils.js";
/** Append a set of key value pairs to a {@link URLSearchParams} object. */
function appendRecordToURLSearchParams(
searchParams: URLSearchParams,
recordToAppend: URLSearchParamsRecord,
): void {
for (const [key, val] of Object.entries(recordToAppend)) {
if (val != null) {
searchParams.set(
key,
Array.isArray(val)
? val.join()
: val instanceof Date
? val.toISOString()
: String(val),
);
}
}
}
/**
* Creates a new Headers object from a {@link HeadersInit} and adds various
* properties to it, some from {@link Config}.
*
* @returns A new Headers object
*/
function getHeaders(config: Config, headersInit?: HeadersInit): Headers {
const agentHeader = "X-Meilisearch-Client";
const packageAgent = `Meilisearch JavaScript (v${PACKAGE_VERSION})`;
const contentType = "Content-Type";
const authorization = "Authorization";
const headers = new Headers(headersInit);
// do not override if user provided the header
if (config.apiKey && !headers.has(authorization)) {
headers.set(authorization, `Bearer ${config.apiKey}`);
}
if (!headers.has(contentType)) {
headers.set(contentType, "application/json");
}
// Creates the custom user agent with information on the package used.
if (config.clientAgents !== undefined) {
const clients = config.clientAgents.concat(packageAgent);
headers.set(agentHeader, clients.join(" ; "));
} else {
headers.set(agentHeader, packageAgent);
}
return headers;
}
// TODO: Convert to Symbol("timeout id") when Node.js 18 is dropped
/** Used to identify whether an error is a timeout error after fetch request. */
const TIMEOUT_ID = {};
/**
* Attach a timeout signal to a {@link RequestInit}, while preserving original
* signal functionality, if there is one.
*
* @remarks
* This could be a short few straight forward lines using {@link AbortSignal.any}
* and {@link AbortSignal.timeout}, but these aren't yet widely supported enough,
* nor polyfill -able, at the time of writing.
* @returns A new function which starts the timeout, which then returns another
* function that clears the timeout
*/
function getTimeoutFn(
requestInit: RequestInit,
ms: number,
): () => (() => void) | void {
const { signal } = requestInit;
const ac = new AbortController();
if (signal != null) {
let acSignalFn: (() => void) | null = null;
if (signal.aborted) {
ac.abort(signal.reason);
} else {
const fn = () => ac.abort(signal.reason);
signal.addEventListener("abort", fn, { once: true });
acSignalFn = () => signal.removeEventListener("abort", fn);
ac.signal.addEventListener("abort", acSignalFn, { once: true });
}
return () => {
if (signal.aborted) {
return;
}
const to = setTimeout(() => ac.abort(TIMEOUT_ID), ms);
const fn = () => {
clearTimeout(to);
if (acSignalFn !== null) {
ac.signal.removeEventListener("abort", acSignalFn);
}
};
signal.addEventListener("abort", fn, { once: true });
return () => {
signal.removeEventListener("abort", fn);
fn();
};
};
}
requestInit.signal = ac.signal;
return () => {
const to = setTimeout(() => ac.abort(TIMEOUT_ID), ms);
return () => clearTimeout(to);
};
}
/** Class used to perform HTTP requests. */
export class HttpRequests {
#url: URL;
#requestInit: HttpRequestsRequestInit;
#customRequestFn?: Config["httpClient"];
#requestTimeout?: Config["timeout"];
constructor(config: Config) {
const host = addTrailingSlash(addProtocolIfNotPresent(config.host));
try {
this.#url = new URL(host);
} catch (error) {
throw new MeiliSearchError("The provided host is not valid", {
cause: error,
});
}
this.#requestInit = {
...config.requestInit,
headers: getHeaders(config, config.requestInit?.headers),
};
this.#customRequestFn = config.httpClient;
this.#requestTimeout = config.timeout;
}
/**
* Combines provided extra {@link RequestInit} headers, provided content type
* and class instance RequestInit headers, prioritizing them in this order.
*
* @returns A new Headers object or the main headers of this class if no
* headers are provided
*/
#getHeaders(extraHeaders?: HeadersInit, contentType?: string): Headers {
if (extraHeaders === undefined && contentType === undefined) {
return this.#requestInit.headers;
}
const headers = new Headers(extraHeaders);
if (contentType !== undefined && !headers.has("Content-Type")) {
headers.set("Content-Type", contentType);
}
for (const [key, val] of this.#requestInit.headers) {
if (!headers.has(key)) {
headers.set(key, val);
}
}
return headers;
}
/**
* Sends a request with {@link fetch} or a custom HTTP client, combining
* parameters and class properties.
*
* @returns A promise containing the response
*/
async #request<T = unknown>({
path,
method,
params,
contentType,
body,
extraRequestInit,
}: MainRequestOptions): Promise<T> {
const url = new URL(path, this.#url);
if (params !== undefined) {
appendRecordToURLSearchParams(url.searchParams, params);
}
const init: RequestInit = {
method,
body:
contentType === undefined || typeof body !== "string"
? JSON.stringify(body)
: body,
...extraRequestInit,
...this.#requestInit,
headers: this.#getHeaders(extraRequestInit?.headers, contentType),
};
const startTimeout =
this.#requestTimeout !== undefined
? getTimeoutFn(init, this.#requestTimeout)
: null;
const stopTimeout = startTimeout?.();
let response: Response;
let responseBody: string;
try {
if (this.#customRequestFn !== undefined) {
// When using a custom HTTP client, the response should already be handled and ready to be returned
return (await this.#customRequestFn(url, init)) as T;
}
response = await fetch(url, init);
responseBody = await response.text();
} catch (error) {
throw new MeiliSearchRequestError(
url.toString(),
Object.is(error, TIMEOUT_ID)
? new MeiliSearchRequestTimeOutError(this.#requestTimeout!, init)
: error,
);
} finally {
stopTimeout?.();
}
const parsedResponse =
responseBody === ""
? undefined
: (JSON.parse(responseBody) as T | MeiliSearchErrorResponse);
if (!response.ok) {
throw new MeiliSearchApiError(
response,
parsedResponse as MeiliSearchErrorResponse | undefined,
);
}
return parsedResponse as T;
}
/** Request with GET. */
get<T = unknown>(options: RequestOptions): Promise<T> {
return this.#request<T>(options);
}
/** Request with POST. */
post<T = unknown>(options: RequestOptions): Promise<T> {
return this.#request<T>({ ...options, method: "POST" });
}
/** Request with PUT. */
put<T = unknown>(options: RequestOptions): Promise<T> {
return this.#request<T>({ ...options, method: "PUT" });
}
/** Request with PATCH. */
patch<T = unknown>(options: RequestOptions): Promise<T> {
return this.#request<T>({ ...options, method: "PATCH" });
}
/** Request with DELETE. */
delete<T = unknown>(options: RequestOptions): Promise<T> {
return this.#request<T>({ ...options, method: "DELETE" });
}
}