-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathhttp-requests.ts
322 lines (282 loc) · 7.84 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import { Config, EnqueuedTaskObject } from './types'
import { PACKAGE_VERSION } from './package-version'
import {
MeiliSearchError,
httpResponseErrorHandler,
httpErrorHandler,
} from './errors'
import { addTrailingSlash, addProtocolIfNotPresent } from './utils'
type queryParams<T> = { [key in keyof T]: string }
function toQueryParams<T extends object>(parameters: T): queryParams<T> {
const params = Object.keys(parameters) as Array<keyof T>
const queryParams = params.reduce<queryParams<T>>((acc, key) => {
const value = parameters[key]
if (value === undefined) {
return acc
} else if (Array.isArray(value)) {
return { ...acc, [key]: value.join(',') }
} else if (value instanceof Date) {
return { ...acc, [key]: value.toISOString() }
}
return { ...acc, [key]: value }
}, {} as queryParams<T>)
return queryParams
}
function constructHostURL(host: string): string {
try {
host = addProtocolIfNotPresent(host)
host = addTrailingSlash(host)
return host
} catch (e) {
throw new MeiliSearchError('The provided host is not valid.')
}
}
function cloneAndParseHeaders(headers: HeadersInit): Record<string, string> {
if (Array.isArray(headers)) {
return headers.reduce(
(acc, headerPair) => {
acc[headerPair[0]] = headerPair[1]
return acc
},
{} as Record<string, string>
)
} else if ('has' in headers) {
const clonedHeaders: Record<string, string> = {}
;(headers as Headers).forEach((value, key) => (clonedHeaders[key] = value))
return clonedHeaders
} else {
return Object.assign({}, headers)
}
}
function createHeaders(config: Config): Record<string, any> {
const agentHeader = 'X-Meilisearch-Client'
const packageAgent = `Meilisearch JavaScript (v${PACKAGE_VERSION})`
const contentType = 'Content-Type'
const authorization = 'Authorization'
const headers = cloneAndParseHeaders(config.requestConfig?.headers ?? {})
// do not override if user provided the header
if (config.apiKey && !headers[authorization]) {
headers[authorization] = `Bearer ${config.apiKey}`
}
if (!headers[contentType]) {
headers['Content-Type'] = 'application/json'
}
// Creates the custom user agent with information on the package used.
if (config.clientAgents && Array.isArray(config.clientAgents)) {
const clients = config.clientAgents.concat(packageAgent)
headers[agentHeader] = clients.join(' ; ')
} else if (config.clientAgents && !Array.isArray(config.clientAgents)) {
// If the header is defined but not an array
throw new MeiliSearchError(
`Meilisearch: The header "${agentHeader}" should be an array of string(s).\n`
)
} else {
headers[agentHeader] = packageAgent
}
return headers
}
class HttpRequests {
headers: Record<string, any>
url: URL
requestConfig?: Config['requestConfig']
httpClient?: Required<Config>['httpClient']
requestTimeout?: number
constructor(config: Config) {
this.headers = createHeaders(config)
this.requestConfig = config.requestConfig
this.httpClient = config.httpClient
this.requestTimeout = config.timeout
try {
const host = constructHostURL(config.host)
this.url = new URL(host)
} catch (e) {
throw new MeiliSearchError('The provided host is not valid.')
}
}
async request({
method,
url,
params,
body,
config = {},
}: {
method: string
url: string
params?: { [key: string]: any }
body?: any
config?: Record<string, any>
}) {
if (typeof fetch === 'undefined') {
require('cross-fetch/polyfill')
}
const constructURL = new URL(url, this.url)
if (params) {
const queryParams = new URLSearchParams()
Object.keys(params)
.filter((x: string) => params[x] !== null)
.map((x: string) => queryParams.set(x, params[x]))
constructURL.search = queryParams.toString()
}
// in case a custom content-type is provided
// do not stringify body
if (!config.headers?.['Content-Type']) {
body = JSON.stringify(body)
}
const headers = { ...this.headers, ...config.headers }
try {
const result = this.fetchWithTimeout(
constructURL.toString(),
{
...config,
...this.requestConfig,
method,
body,
headers,
},
this.requestTimeout
)
// When using a custom HTTP client, the response is returned to allow the user to parse/handle it as they see fit
if (this.httpClient) {
return await result
}
const response = await result.then((res: any) =>
httpResponseErrorHandler(res)
)
const parsedBody = await response.json().catch(() => undefined)
return parsedBody
} catch (e: any) {
const stack = e.stack
httpErrorHandler(e, stack, constructURL.toString())
}
}
async fetchWithTimeout(
url: string,
options: Record<string, any> | RequestInit | undefined,
timeout: HttpRequests['requestTimeout']
): Promise<Response> {
return new Promise((resolve, reject) => {
const fetchFn = this.httpClient ? this.httpClient : fetch
const fetchPromise = fetchFn(url, options)
const promises: Array<Promise<any>> = [fetchPromise]
// TimeoutPromise will not run if undefined or zero
let timeoutId: ReturnType<typeof setTimeout>
if (timeout) {
const timeoutPromise = new Promise((_, reject) => {
timeoutId = setTimeout(() => {
reject(new Error('Error: Request Timed Out'))
}, timeout)
})
promises.push(timeoutPromise)
}
Promise.race(promises)
.then(resolve)
.catch(reject)
.finally(() => {
clearTimeout(timeoutId)
})
})
}
async get(
url: string,
params?: { [key: string]: any },
config?: Record<string, any>
): Promise<void>
async get<T = any>(
url: string,
params?: { [key: string]: any },
config?: Record<string, any>
): Promise<T>
async get(
url: string,
params?: { [key: string]: any },
config?: Record<string, any>
): Promise<any> {
return await this.request({
method: 'GET',
url,
params,
config,
})
}
async post<T = any, R = EnqueuedTaskObject>(
url: string,
data?: T,
params?: { [key: string]: any },
config?: Record<string, any>
): Promise<R>
async post(
url: string,
data?: any,
params?: { [key: string]: any },
config?: Record<string, any>
): Promise<any> {
return await this.request({
method: 'POST',
url,
body: data,
params,
config,
})
}
async put<T = any, R = EnqueuedTaskObject>(
url: string,
data?: T,
params?: { [key: string]: any },
config?: Record<string, any>
): Promise<R>
async put(
url: string,
data?: any,
params?: { [key: string]: any },
config?: Record<string, any>
): Promise<any> {
return await this.request({
method: 'PUT',
url,
body: data,
params,
config,
})
}
async patch(
url: string,
data?: any,
params?: { [key: string]: any },
config?: Record<string, any>
): Promise<any> {
return await this.request({
method: 'PATCH',
url,
body: data,
params,
config,
})
}
async delete(
url: string,
data?: any,
params?: { [key: string]: any },
config?: Record<string, any>
): Promise<EnqueuedTaskObject>
async delete<T>(
url: string,
data?: any,
params?: { [key: string]: any },
config?: Record<string, any>
): Promise<T>
async delete(
url: string,
data?: any,
params?: { [key: string]: any },
config?: Record<string, any>
): Promise<any> {
return await this.request({
method: 'DELETE',
url,
body: data,
params,
config,
})
}
}
export { HttpRequests, toQueryParams }