-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRequete.ts
393 lines (348 loc) · 10.3 KB
/
Requete.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
import { Adapter, createAdapter } from 'requete/adapter'
import {
getUri,
Logger,
mergeHeaders,
pick,
RequestError,
stringifyUrl,
} from 'requete/shared'
import { TimeoutAbortController } from './AbortController'
import { compose } from './compose'
export type Method =
| 'GET'
| 'DELETE'
| 'HEAD'
| 'OPTIONS'
| 'POST'
| 'PUT'
| 'PATCH'
export type RequestBody =
| BodyInit
| null
| Record<string, any>
| Record<string, any>[]
export type RequestQueryRecord = Record<
string,
| string
| number
| boolean
| null
| undefined
| Array<string | number | boolean>
>
export type RequestQuery = string | URLSearchParams | RequestQueryRecord
export interface RequestConfig {
baseURL?: string
/** request timeout (ms) */
timeout?: number
/** response body type */
responseType?: 'json' | 'formData' | 'text' | 'blob' | 'arrayBuffer'
/** A string indicating how the request will interact with the browser's cache to set request's cache. */
cache?: RequestCache
/** A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. */
credentials?: RequestCredentials
/** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */
headers?: HeadersInit
/** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */
integrity?: string
/** A boolean to set request's keepalive. */
keepalive?: boolean
/** A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. */
mode?: RequestMode
/** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */
redirect?: RequestRedirect
/** A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. */
referrer?: string
/** A referrer policy to set request's referrerPolicy. */
referrerPolicy?: ReferrerPolicy
/** enable logger or set logger level # */
verbose?: boolean | number
/**
* parse json function
* (for transform response)
* @default JSON.parse
*/
toJSON?(body: string): any
}
export interface IRequest extends Omit<RequestConfig, 'verbose'> {
url: string
/**
* A string to set request's method.
* @default GET
*/
method?: Method
/** A string or object to set querystring of url */
params?: RequestQuery
/** request`s body */
data?: RequestBody
/**
* A TimeoutAbortController to set request's signal.
* @default TimeoutAbortController
*/
abort?: TimeoutAbortController | null
/** specify request adapter */
adapter?: Adapter
/** flexible custom field */
custom?: Record<string, any>
}
/** {@link https://developer.mozilla.org/en-US/docs/Web/API/Response} */
export interface IResponse<Data = any> {
headers: Headers
ok: boolean
redirected: boolean
status: number
statusText: string
type: ResponseType
url: string
data: Data
responseText?: string
}
export interface IContext<Data = any> extends IResponse<Data> {
/**
* request config.
* and empty `Headers` object as default
*/
request: IRequest & { method: Method; headers: Headers }
/**
* set `ctx.request.headers`
*
* *And header names are matched by case-insensitive byte sequence.*
*
* @example
* ```ts
* // set a header
* ctx.set('name', '<value>')
*
* // remove a header
* ctx.set('name', null)
* ctx.set('name')
*
* // set headers
* ctx.set({ name1: '<value>', name2: '<value>' })
* ```
*/
set(headerOrName: HeadersInit | string, value?: string | null): this
/**
* Add extra params to `request.url`.
* If there are duplicate keys, then the original key-values will be removed.
*/
params(params: RequestQuery): this
/**
* get `ctx.request.abort`,
* and **create one if not exist**
* @throws {RequestError}
*/
abort(): TimeoutAbortController
/** throw {@link RequestError} */
throw(e: string | Error): void
/**
* Assign to current context
*/
assign(context: Partial<IContext>): void
/**
* Replay current request
* And assign new context to current, with replay`s response
*/
replay(): Promise<void>
}
export type Middleware = (
ctx: IContext,
next: () => Promise<void>
) => Promise<void>
type AliasConfig = Omit<IRequest, 'url' | 'data'>
export class Requete {
static defaults: RequestConfig = {
timeout: 0,
responseType: 'json',
headers: {
Accept: 'application/json, text/plain, */*',
},
verbose: 1,
toJSON: (text: string | null | undefined) => {
if (text) return JSON.parse(text)
},
}
private configs?: RequestConfig
private adapter: Adapter
private middlewares: Middleware[] = []
logger: Logger
constructor(config?: RequestConfig) {
this.configs = Object.assign({ method: 'GET' }, Requete.defaults, config)
this.adapter = createAdapter()
this.logger = new Logger(
'Requete',
this.configs.verbose === true ? 2 : Number(this.configs.verbose ?? 0)
)
}
/**
* add middleware function
*
* @attention
* - The calling order of middleware should follow the **Onion Model**.
* like {@link https://github.com/koajs/koa/blob/master/docs/guide.md#writing-middleware Koajs}.
* - `next()` must be called asynchronously in middleware
*
* @example
* ```ts
* http.use(async (ctx, next) => {
* // set request header
* ctx.set('Authorization', '<token>')
*
* // wait for request responding
* await next()
*
* // transformed response body
* console.log(ctx.data)
*
* // throw a request error
* if (!ctx.data) ctx.throw('no response data')
* })
* ```
*/
use(middleware: Middleware) {
this.middlewares.push(middleware)
this.logger.info(
`Use middleware #${this.middlewares.length}:`,
middleware.name || middleware
)
return this
}
private createRequest(config: IRequest) {
const request: IRequest = Object.assign({}, this.configs, config)
request.url = getUri(request)
request.headers = mergeHeaders(
Requete.defaults.headers,
this.configs?.headers,
config.headers
)
// add default AbortController for timeout
if (!request.abort && request.timeout && TimeoutAbortController.supported) {
request.abort = new TimeoutAbortController(request.timeout)
}
return request as IContext['request']
}
private createContext<D>(config: IRequest) {
const request = this.createRequest(config)
const doRequest = this.request.bind(this)
const ctx: IContext<D> = {
request,
status: -1,
data: undefined as D,
ok: false,
redirected: false,
headers: undefined as unknown as Headers,
statusText: undefined as unknown as string,
type: undefined as unknown as ResponseType,
url: request.url,
set(headerOrName, value) {
if (this.status !== -1)
this.throw('Cannot set request headers after next().')
let headers = this.request.headers
if (typeof headerOrName === 'string') {
value == null
? headers.delete(headerOrName)
: headers.set(headerOrName, value)
} else {
headers = mergeHeaders(headers, headerOrName)
}
this.request.headers = headers
return this
},
params(params) {
this.request.url = stringifyUrl(this.request.url, params, false)
return this
},
abort() {
if (!this.request.abort) {
if (this.status !== -1)
this.throw('Cannot set abortSignal after next().')
this.request.abort = new TimeoutAbortController(
this.request.timeout ?? 0
)
}
return this.request.abort
},
throw(e) {
if (e instanceof RequestError) throw e
throw new RequestError(e, this)
},
assign(context) {
Object.assign(this, context)
},
async replay() {
// count replay #
this.request.custom = Object.assign({}, this.request.custom, {
replay: (this.request.custom?.replay ?? 0) + 1,
})
const context = await doRequest(this.request)
this.assign(context)
},
}
return ctx
}
private async invoke(ctx: IContext) {
this.logger.request(ctx)
const adapter = ctx.request.adapter ?? this.adapter
const response = await adapter.request(ctx)
// assign to ctx
Object.assign(
ctx,
pick(response, [
'ok',
'status',
'statusText',
'headers',
'data',
'responseText',
'redirected',
'type',
'url',
])
)
if (ctx.request.responseType === 'json') {
ctx.data = ctx.request.toJSON!(response.data)
}
}
async request<D = any>(config: IRequest) {
// create context
const context = this.createContext<D>(config)
// exec middleware
try {
await compose(this.middlewares)(context, this.invoke.bind(this))
if (!context.ok) {
context.throw(
`${context.request.method} ${context.url} ${context.status} (${context.statusText})`
)
}
this.logger.response(context)
return context
} catch (e: any) {
this.logger.error(e)
throw e
} finally {
context.request.abort?.clear()
}
}
get<D = any>(url: string, config?: AliasConfig) {
return this.request<D>({ ...config, url, method: 'GET' })
}
delete<D = any>(url: string, config?: AliasConfig) {
return this.request<D>({ ...config, url, method: 'DELETE' })
}
head<D = any>(url: string, config?: AliasConfig) {
return this.request<D>({ ...config, url, method: 'HEAD' })
}
options<D = any>(url: string, config?: AliasConfig) {
return this.request<D>({ ...config, url, method: 'OPTIONS' })
}
post<D = any>(url: string, data?: RequestBody, config?: AliasConfig) {
return this.request<D>({ ...config, url, data, method: 'POST' })
}
put<D = any>(url: string, data?: RequestBody, config?: AliasConfig) {
return this.request<D>({ ...config, url, data, method: 'PUT' })
}
patch<D = any>(url: string, data?: RequestBody, config?: AliasConfig) {
return this.request<D>({ ...config, url, data, method: 'PATCH' })
}
}