-
Notifications
You must be signed in to change notification settings - Fork 201
Expand file tree
/
Copy pathfetch.ts
More file actions
261 lines (232 loc) · 7.17 KB
/
fetch.ts
File metadata and controls
261 lines (232 loc) · 7.17 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
import type { Cacheable } from "cacheable";
import {
type RequestInit,
type Response as UndiciResponse,
fetch as undiciFetch,
} from "undici";
export type FetchOptions = Omit<RequestInit, "cache"> & {
cache: Cacheable;
};
/**
* Fetch data from a URL with optional request options.
* @param {string} url The URL to fetch.
* @param {FetchOptions} options Optional request options. The `cacheable` property is required and should be an
* instance of `Cacheable` or a `CacheableOptions` object.
* @returns {Promise<UndiciResponse>} The response from the fetch.
*/
export async function fetch(
url: string,
options: FetchOptions,
): Promise<UndiciResponse> {
if (!options.cache) {
throw new Error("Fetch options must include a cache instance or options.");
}
const fetchOptions: RequestInit = {
...options,
cache: "no-cache",
};
// Skip caching for POST, PATCH, and HEAD requests
if (
options.method === "POST" ||
options.method === "PATCH" ||
options.method === "HEAD"
) {
const response = await undiciFetch(url, fetchOptions);
/* c8 ignore next 3 */
if (!response.ok) {
throw new Error(`Fetch failed with status ${response.status}`);
}
return response;
}
// Create a cache key that includes the method
const cacheKey = `${options.method || "GET"}:${url}`;
const cachedData = await options.cache.getOrSet(cacheKey, async () => {
// Perform the fetch operation
const response = await undiciFetch(url, fetchOptions);
/* c8 ignore next 3 */
if (!response.ok) {
throw new Error(`Fetch failed with status ${response.status}`);
}
// Convert response to cacheable format
const body = await response.text();
return {
body,
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
};
});
// Reconstruct Response object from cached data
/* c8 ignore next 3 */
if (!cachedData) {
throw new Error("Failed to get or set cache data");
}
return new Response(cachedData.body, {
status: cachedData.status,
statusText: cachedData.statusText,
headers: cachedData.headers,
}) as UndiciResponse;
}
export type DataResponse<T = unknown> = {
data: T;
response: UndiciResponse;
};
// Keep GetResponse as an alias for backward compatibility
export type GetResponse<T = unknown> = DataResponse<T>;
/**
* Perform a GET request to a URL with optional request options.
* @param {string} url The URL to fetch.
* @param {Omit<FetchOptions, 'method'>} options Optional request options. The `cache` property is required.
* @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
*/
export async function get<T = unknown>(
url: string,
options: Omit<FetchOptions, "method">,
): Promise<DataResponse<T>> {
const response = await fetch(url, { ...options, method: "GET" });
const text = await response.text();
let data: T;
try {
data = JSON.parse(text) as T;
} catch {
// If not JSON, return as is
data = text as T;
}
// Create a new response with the text already consumed
const newResponse = new Response(text, {
status: response.status,
statusText: response.statusText,
headers: response.headers as HeadersInit,
}) as UndiciResponse;
return {
data,
response: newResponse,
};
}
/**
* Perform a POST request to a URL with data and optional request options.
* @param {string} url The URL to fetch.
* @param {unknown} data The data to send in the request body.
* @param {Omit<FetchOptions, 'method' | 'body'>} options Optional request options. The `cache` property is required.
* @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
*/
export async function post<T = unknown>(
url: string,
data: unknown,
options: Omit<FetchOptions, "method" | "body">,
): Promise<DataResponse<T>> {
// Automatically stringify data if it's an object and set appropriate headers
let body: BodyInit | undefined;
const headers = { ...options.headers } as Record<string, string>;
if (typeof data === "string") {
body = data;
} else if (
data instanceof FormData ||
data instanceof URLSearchParams ||
data instanceof Blob
) {
body = data as BodyInit;
} else {
// Assume it's JSON data
body = JSON.stringify(data);
// Set Content-Type to JSON if not already set
if (!headers["Content-Type"] && !headers["content-type"]) {
headers["Content-Type"] = "application/json";
}
}
const response = await fetch(url, {
...options,
headers,
body: body as RequestInit["body"],
method: "POST",
});
const text = await response.text();
let responseData: T;
try {
responseData = JSON.parse(text) as T;
} catch {
// If not JSON, return as is
responseData = text as T;
}
// Create a new response with the text already consumed
const newResponse = new Response(text, {
status: response.status,
statusText: response.statusText,
headers: response.headers as HeadersInit,
}) as UndiciResponse;
return {
data: responseData,
response: newResponse,
};
}
/**
* Perform a PATCH request to a URL with data and optional request options.
* @param {string} url The URL to fetch.
* @param {unknown} data The data to send in the request body.
* @param {Omit<FetchOptions, 'method' | 'body'>} options Optional request options. The `cache` property is required.
* @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
*/
export async function patch<T = unknown>(
url: string,
data: unknown,
options: Omit<FetchOptions, "method" | "body">,
): Promise<DataResponse<T>> {
// Automatically stringify data if it's an object and set appropriate headers
let body: BodyInit | undefined;
const headers = { ...options.headers } as Record<string, string>;
if (typeof data === "string") {
body = data;
} else if (
data instanceof FormData ||
data instanceof URLSearchParams ||
data instanceof Blob
) {
body = data as BodyInit;
} else {
// Assume it's JSON data
body = JSON.stringify(data);
// Set Content-Type to JSON if not already set
if (!headers["Content-Type"] && !headers["content-type"]) {
headers["Content-Type"] = "application/json";
}
}
const response = await fetch(url, {
...options,
headers,
body: body as RequestInit["body"],
method: "PATCH",
});
const text = await response.text();
let responseData: T;
try {
responseData = JSON.parse(text) as T;
} catch {
// If not JSON, return as is
responseData = text as T;
}
// Create a new response with the text already consumed
const newResponse = new Response(text, {
status: response.status,
statusText: response.statusText,
headers: response.headers as HeadersInit,
}) as UndiciResponse;
return {
data: responseData,
response: newResponse,
};
}
/**
* Perform a HEAD request to a URL with optional request options.
* @param {string} url The URL to fetch.
* @param {Omit<FetchOptions, 'method'>} options Optional request options. The `cache` property is required.
* @returns {Promise<UndiciResponse>} The response from the fetch (no body).
*/
export async function head(
url: string,
options: Omit<FetchOptions, "method">,
): Promise<UndiciResponse> {
const response = await fetch(url, { ...options, method: "HEAD" });
return response;
}
export type Response = UndiciResponse;
export type { RequestInit as FetchRequestInit } from "undici";