-
-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathapi.ts
More file actions
285 lines (246 loc) · 8.15 KB
/
api.ts
File metadata and controls
285 lines (246 loc) · 8.15 KB
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
import { attach, createEffect } from 'effector';
import { normalizeStaticOrReactive, StaticOrReactive } from '../libs/patronus';
import { drain, NonOptionalKeys } from '../libs/lohyphen';
import {
ConfigurationError,
HttpError,
InvalidDataError,
NetworkError,
PreparationError,
TimeoutError,
} from '../errors/type';
import { preparationError, invalidDataError } from '../errors/create_error';
import {
formatUrl,
mergeRecords,
formatHeaders,
isNullBodyStatus,
type FetchApiRecord,
mergeQueryStrings,
} from './lib';
import { requestFx, type RequestError } from './request';
export type HttpMethod =
| 'HEAD'
| 'GET'
| 'POST'
| 'PUT'
| 'PATCH'
| 'DELETE'
| 'QUERY'
| 'OPTIONS';
export type RequestBody = Blob | BufferSource | FormData | string;
// These settings can be defined only statically
export interface StaticOnlyRequestConfig<B> {
method: StaticOrReactive<HttpMethod>;
mapBody(body: B): RequestBody;
}
// These settings can be defined once — statically or dynamically
export interface ExclusiveRequestConfigShared {
url: string;
credentials?: RequestCredentials;
abortController?: AbortController;
}
export interface ExclusiveRequestConfig<
B,
> extends ExclusiveRequestConfigShared {
body?: B;
}
// These settings can be defined twice — both statically and dynamically, they will be merged
export interface InclusiveRequestConfig {
query?: FetchApiRecord | string;
headers?: FetchApiRecord;
}
export type CreationRequestConfigShared<E> = {
[key in keyof E]?: StaticOrReactive<E[key]>;
} & {
[key in keyof InclusiveRequestConfig]?: StaticOrReactive<
InclusiveRequestConfig[key]
>;
};
type CreationRequestConfig<B> = CreationRequestConfigShared<
ExclusiveRequestConfig<B>
> &
StaticOnlyRequestConfig<B>;
type DynamicRequestConfig<B> = ExclusiveRequestConfig<B> &
Required<InclusiveRequestConfig>;
interface ApiConfigResponse<P> {
/**
* Transforms Response
*
* @example
*
* const callApiFx = createApiRequest({
* prepare: { extract: (response) => response.json() },
* })
*/
extract: (response: Response) => Promise<P>;
transformError?: (
error: NetworkError | HttpError
) => NetworkError | HttpError;
/** Configuration of allowed response statuses */
status?: {
expected: number | number[];
};
}
interface ApiConfig<B, R extends CreationRequestConfig<B>, P> {
/** Rules to create Request */
request: R;
/** Rules to handle Response */
response: ApiConfigResponse<P>;
}
export type ApiRequestError =
| ConfigurationError
| TimeoutError
| PreparationError
| NetworkError
| HttpError;
export type JsonApiRequestError = ApiRequestError | InvalidDataError;
export type ApiRequestErrorWithMeta = {
error: ApiRequestError;
responseMeta?: { headers: Headers };
};
export function createApiRequest<
R extends CreationRequestConfig<B>,
P,
B = RequestBody,
>(config: ApiConfig<B, R, P>) {
type ApiRequestParams = Omit<ExclusiveRequestConfig<B>, NonOptionalKeys<R>> &
InclusiveRequestConfig;
type ApiRequestResult = P;
const prepareFx = createEffect(config.response.extract);
const apiRequestFx = createEffect<
DynamicRequestConfig<B> & {
method: HttpMethod;
},
{ result: ApiRequestResult; meta: { headers: Headers } },
ApiRequestErrorWithMeta
>(
async ({
url,
method,
query,
headers,
credentials,
body,
abortController,
}) => {
const mappedBody = body ? config.request.mapBody(body) : null;
const request = new Request(formatUrl(url, query), {
method,
headers: formatHeaders(headers),
credentials,
body: mappedBody,
signal: abortController?.signal,
});
const response = await requestFx(request).catch((cause: RequestError) => {
// cause is { error, responseMeta? }
const transformedError =
config.response.transformError?.(cause.error) ?? cause.error;
// Re-throw with responseMeta preserved
throw { error: transformedError, responseMeta: cause.responseMeta };
});
const responseHeaders = response.headers;
// For null body statuses (101, 103, 204, 205, 304), the Response constructor
// throws if a body is provided, so we must use null body for these statuses.
const hasNullBodyStatus = isNullBodyStatus(response.status);
// Determine how to handle body cloning based on environment capabilities
let responseForPrepare: Response;
let responseForError: Response | null = null;
let streamForError: ReadableStream | null = null;
if (hasNullBodyStatus) {
responseForPrepare = new Response(null, response);
} else if (response.body && typeof response.body.tee === 'function') {
// Streams API available (browsers, edge runtimes)
const [forPrepare, forError] = response.body.tee();
responseForPrepare = new Response(forPrepare, response);
streamForError = forError;
} else {
// Fallback for React Native (no Streams API)
responseForPrepare = response.clone();
responseForError = response;
}
const prepared = await prepareFx(responseForPrepare).then(
async (result) => {
await drain(streamForError);
return result;
},
async (cause) => {
let errorResponseText = '';
if (streamForError) {
errorResponseText = await new Response(streamForError).text();
} else if (responseForError) {
errorResponseText = await responseForError.text();
}
throw {
error: preparationError({
response: errorResponseText,
reason: cause?.message ?? null,
}),
responseMeta: { headers: responseHeaders },
};
}
);
if (config.response.status) {
const expected = Array.isArray(config.response.status.expected)
? config.response.status.expected
: [config.response.status.expected];
if (!expected.includes(response.status)) {
throw {
error: invalidDataError({
validationErrors: [
`Expected response status has to be one of [${expected.join(
', '
)}], got ${response.status}`,
],
response: prepared,
}),
responseMeta: { headers: responseHeaders },
};
}
}
return { result: prepared, meta: { headers: response.headers } };
}
);
return attach({
source: {
url: normalizeStaticOrReactive(config.request.url),
method: normalizeStaticOrReactive(config.request.method),
query: normalizeStaticOrReactive(config.request.query),
headers: normalizeStaticOrReactive(config.request.headers),
credentials: normalizeStaticOrReactive(config.request.credentials),
body: normalizeStaticOrReactive(config.request.body),
},
mapParams(dynamicConfig: ApiRequestParams, staticConfig) {
// Exclusive settings
const url: string =
staticConfig.url ??
// @ts-expect-error TS cannot infer type correctly, but there is always field in staticConfig or dynamicConfig
dynamicConfig.url;
const credentials: RequestCredentials =
staticConfig.credentials ??
// @ts-expect-error TS cannot infer type correctly, but there is always field in staticConfig or dynamicConfig
dynamicConfig.credentials;
const body: B =
staticConfig.body ??
// @ts-expect-error TS cannot infer type correctly, but there is always field in staticConfig or dynamicConfig
dynamicConfig.body;
// Inclusive settings
const query = mergeQueryStrings(staticConfig.query, dynamicConfig.query);
const headers = mergeRecords(staticConfig.headers, dynamicConfig.headers);
// Other settings
const { method } = staticConfig;
// @ts-expect-error
const { abortController } = dynamicConfig;
return {
url,
method: method!, // TODO: fix type inference here
query,
headers,
credentials,
body,
abortController,
};
},
effect: apiRequestFx,
});
}