-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
fetcher.ts
208 lines (189 loc) · 5.33 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
import { writable } from 'svelte/store'
import type { Unsubscriber } from 'svelte/store'
import { getFetchParams, mergeRequestInit } from '../fetcher.js'
import type {
Request,
TypedWrappedFetch,
_TypedWrappedFetch,
RealFetch,
OpArgType,
FetchConfig,
OpErrorType,
OpenapiPaths,
Method,
} from '../types.js'
import type { ApiRequest, ApiResponse, SvelteCreateFetch } from './types.js'
import { ApiError, LimitedResponse } from '../types.js'
const JSON_CONTENT_TYPES = ['application/json', 'application/ld+json']
async function getResponseBody(response: LimitedResponse) {
// no content
if (response.status === 204) {
return undefined
}
const contentType = response.headers.get('content-type')
if (contentType && JSON_CONTENT_TYPES.includes(contentType)) {
return await response.json()
} else if (contentType && contentType.indexOf('text') === -1) {
// if the response is neither JSON nor text, return binary data as is
// @ts-ignore
return await response.blob()
}
const text = await response.text()
try {
return JSON.parse(text)
} catch (e) {
return text
}
}
/***
* Make an API call and compose an ApiResponse object from the result
* @param request - Request wrapper
*/
async function fetchAndParse<R>(request: Request): Promise<ApiResponse<R>> {
const { url, init } = getFetchParams(request)
try {
const response = await request.realFetch(url, init)
try {
const body = await getResponseBody(response)
if (response.ok) {
return {
status: response.status,
data: body as R,
ok: true,
}
} else {
return {
status: response.status,
data: body as R,
ok: false,
}
}
} catch (e) {
console.warn('Failed to parse the response body', e)
return {
status: -2,
data: undefined,
ok: false,
}
}
} catch (e) {
console.warn('Failed to make an API request', e)
return {
status: -1,
data: undefined,
ok: false,
}
}
}
function fetchUrl<R>(request: Request) {
// eslint-disable-next-line @typescript-eslint/no-empty-function
const ready = writable<Promise<ApiResponse<R>>>(new Promise(() => {}))
const resp = writable<ApiResponse<R> | undefined>()
let unsubscribe: Unsubscriber | undefined = undefined
const retVal = {
resp,
ready,
reload,
// eslint-disable-next-line @typescript-eslint/no-empty-function
// Deprecated field. Will be removed in one of the major updates
onData: new Promise(() => {}),
// eslint-disable-next-line @typescript-eslint/no-empty-function
result: new Promise(() => {}),
} as ApiRequest<R>
const apiCall: () => Promise<ApiResponse<R>> = () => {
const promise = new Promise<ApiResponse<R>>(async (resolve) => {
const result = await fetchAndParse<R>(request)
unsubscribe = resp.subscribe((r) => {
if (typeof r !== 'undefined' && r.data === result.data) {
resolve(r)
retVal.result = Promise.resolve(r)
retVal.onData = retVal.result
if (unsubscribe) {
unsubscribe()
unsubscribe = undefined
}
}
})
resp.set(result)
})
ready.set(promise)
return promise
}
async function reload() {
if (unsubscribe) {
unsubscribe()
unsubscribe = undefined
}
const apiCallPromise = apiCall()
retVal.result = apiCallPromise
retVal.onData = apiCallPromise
return apiCallPromise
}
retVal.result = apiCall()
retVal.onData = retVal.result
retVal.reload = reload
return retVal
}
function createFetch<OP>(fetch: _TypedWrappedFetch<OP>): TypedWrappedFetch<OP> {
const fun = (
payload: OpArgType<OP>,
realFetch?: RealFetch,
init?: RequestInit,
) => {
try {
return fetch(payload, realFetch, 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>
}
}
fun._name = ''
return fun
}
function fetcher<Paths>() {
let baseUrl = ''
let defaultInit: RequestInit = {}
return {
configure: (config: FetchConfig) => {
baseUrl = config.baseUrl || ''
defaultInit = config.init || {}
},
path: <P extends keyof Paths>(path: P) => ({
method: <M extends keyof Paths[P]>(method: M) => ({
create: function (queryParams?: Record<string, true | 1>) {
const fn = createFetch((payload, realFetch, init) =>
// @ts-ignore
fetchUrl({
baseUrl: baseUrl || '',
path: path as string,
method: method as Method,
queryParams: Object.keys(queryParams || {}),
payload,
init: mergeRequestInit(defaultInit, init),
realFetch: realFetch || fetch,
}),
)
fn._name = `${String(method).toUpperCase()} ${String(path)}`
return fn
} as unknown as SvelteCreateFetch<M, Paths[P][M]>,
}),
}),
}
}
export const Apity = {
for: <Paths extends OpenapiPaths<Paths>>() => fetcher<Paths>(),
}