-
Notifications
You must be signed in to change notification settings - Fork 52
/
fetcher.ts
262 lines (223 loc) · 6.19 KB
/
fetcher.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
import {
ApiError,
ApiResponse,
CreateFetch,
CustomRequestInit,
Fetch,
FetchConfig,
Method,
Middleware,
OpArgType,
OpenapiPaths,
OpErrorType,
Request,
_TypedFetch,
TypedFetch,
} from './types'
const sendBody = (method: Method) =>
method === 'post' ||
method === 'put' ||
method === 'patch' ||
method === 'delete'
function queryString(params: Record<string, unknown>): string {
const qs: string[] = []
const encode = (key: string, value: unknown) =>
`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`
Object.keys(params).forEach((key) => {
const value = params[key]
if (value != null) {
if (Array.isArray(value)) {
value.forEach((value) => qs.push(encode(key, value)))
} else {
qs.push(encode(key, value))
}
}
})
if (qs.length > 0) {
return `?${qs.join('&')}`
}
return ''
}
function getPath(path: string, payload: Record<string, any>) {
return path.replace(/\{([^}]+)\}/g, (_, key) => {
const value = encodeURIComponent(payload[key])
delete payload[key]
return value
})
}
function getQuery(
method: Method,
payload: Record<string, any>,
query: string[],
) {
let queryObj = {} as any
if (sendBody(method)) {
query.forEach((key) => {
queryObj[key] = payload[key]
delete payload[key]
})
} else {
queryObj = { ...payload }
}
return queryString(queryObj)
}
function getHeaders(init?: HeadersInit) {
const headers = new Headers(init)
if (!headers.has('Content-Type')) {
headers.append('Content-Type', 'application/json')
}
if (!headers.has('Accept')) {
headers.append('Accept', 'application/json')
}
return headers
}
function getBody(method: Method, payload: any) {
const body = sendBody(method) ? JSON.stringify(payload) : undefined
// if delete don't send body if empty
return method === 'delete' && body === '{}' ? undefined : body
}
function mergeRequestInit(
first?: RequestInit,
second?: RequestInit,
): RequestInit {
const headers = new Headers(first?.headers)
const other = new Headers(second?.headers)
for (const key of other.keys()) {
const value = other.get(key)
if (value != null) {
headers.set(key, value)
}
}
return { ...first, ...second, headers }
}
function getFetchParams(request: Request) {
// clone payload
// if body is a top level array [ 'a', 'b', param: value ] with param values
// using spread [ ...payload ] returns [ 'a', 'b' ] and skips custom keys
// cloning with Object.assign() preserves all keys
const payload = Object.assign(
Array.isArray(request.payload) ? [] : {},
request.payload,
)
const path = getPath(request.path, payload)
const query = getQuery(request.method, payload, request.queryParams)
const headers = getHeaders(request.init?.headers)
const url = request.baseUrl + path + query
const init = {
...request.init,
method: request.method.toUpperCase(),
headers,
body: getBody(request.method, payload),
}
return { url, init }
}
async function getResponseData(response: Response) {
const contentType = response.headers.get('content-type')
if (contentType && contentType.indexOf('application/json') !== -1) {
return await response.json()
}
const text = await response.text()
try {
return JSON.parse(text)
} catch (e) {
return text
}
}
async function fetchJson(url: string, init: RequestInit): Promise<ApiResponse> {
const response = await fetch(url, init)
const data = await getResponseData(response)
const result = {
headers: response.headers,
url: response.url,
ok: response.ok,
status: response.status,
statusText: response.statusText,
data,
}
if (result.ok) {
return result
}
throw new ApiError(result)
}
function wrapMiddlewares(middlewares: Middleware[], fetch: Fetch): Fetch {
type Handler = (
index: number,
url: string,
init: CustomRequestInit,
) => Promise<ApiResponse>
const handler: Handler = async (index, url, init) => {
if (middlewares == null || index === middlewares.length) {
return fetch(url, init)
}
const current = middlewares[index]
init = init || { headers: getHeaders() }
return await current(url, init, (nextUrl, nextInit) =>
handler(index + 1, nextUrl, nextInit),
)
}
return (url, init) => handler(0, url, init)
}
async function fetchUrl<R>(request: Request) {
const { url, init } = getFetchParams(request)
const response = await request.fetch(url, init)
return response as ApiResponse<R>
}
function createFetch<OP>(fetch: _TypedFetch<OP>): TypedFetch<OP> {
const fun = async (payload: OpArgType<OP>, init?: RequestInit) => {
try {
return await fetch(payload, init)
} catch (err) {
if (err instanceof ApiError) {
throw new fun.Error(err)
}
throw err
}
}
fun.Error = class extends ApiError {
constructor(error: ApiError) {
super(error)
Object.setPrototypeOf(this, new.target.prototype)
}
getActualType() {
return {
status: this.status,
data: this.data,
} as OpErrorType<OP>
}
}
return fun
}
function fetcher<Paths>() {
let baseUrl = ''
let defaultInit: RequestInit = {}
const middlewares: Middleware[] = []
const fetch = wrapMiddlewares(middlewares, fetchJson)
return {
configure: (config: FetchConfig) => {
baseUrl = config.baseUrl || ''
defaultInit = config.init || {}
middlewares.splice(0)
middlewares.push(...(config.use || []))
},
use: (mw: Middleware) => middlewares.push(mw),
path: <P extends keyof Paths>(path: P) => ({
method: <M extends keyof Paths[P]>(method: M) => ({
create: ((queryParams?: Record<string, true | 1>) =>
createFetch((payload, init) =>
fetchUrl({
baseUrl: baseUrl || '',
path: path as string,
method: method as Method,
queryParams: Object.keys(queryParams || {}),
payload,
init: mergeRequestInit(defaultInit, init),
fetch,
}),
)) as CreateFetch<M, Paths[P][M]>,
}),
}),
}
}
export const Fetcher = {
for: <Paths extends OpenapiPaths<Paths>>() => fetcher<Paths>(),
}