-
Notifications
You must be signed in to change notification settings - Fork 201
Expand file tree
/
Copy pathindex.ts
More file actions
225 lines (200 loc) · 6.09 KB
/
index.ts
File metadata and controls
225 lines (200 loc) · 6.09 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
import { Cacheable, type CacheableOptions } from "cacheable";
import { Hookified, type HookifiedOptions } from "hookified";
import {
type DataResponse,
type FetchOptions,
type FetchRequestInit,
type Response as FetchResponse,
fetch,
} from "./fetch.js";
export type CacheableNetOptions = {
cache?: Cacheable | CacheableOptions;
} & HookifiedOptions;
export class CacheableNet extends Hookified {
private _cache: Cacheable = new Cacheable();
constructor(options?: CacheableNetOptions) {
super(options);
if (options?.cache) {
this._cache =
options.cache instanceof Cacheable
? options.cache
: new Cacheable(options.cache);
}
}
public get cache(): Cacheable {
return this._cache;
}
public set cache(value: Cacheable) {
this._cache = value;
}
/**
* Fetch data from a URL with optional request options. Will use the cache that is already set in the instance.
* @param {string} url The URL to fetch.
* @param {FetchRequestInit} options Optional request options.
* @returns {Promise<FetchResponse>} The response from the fetch.
*/
public async fetch(
url: string,
options?: FetchRequestInit,
): Promise<FetchResponse> {
const fetchOptions: FetchOptions = {
...options,
cache: this._cache,
};
return fetch(url, fetchOptions);
}
/**
* Perform a GET request to a URL with optional request options. Will use the cache that is already set in the instance.
* @param {string} url The URL to fetch.
* @param {Omit<FetchRequestInit, 'method'>} options Optional request options (method will be set to GET).
* @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
*/
public async get<T = unknown>(
url: string,
options?: Omit<FetchRequestInit, "method">,
): Promise<DataResponse<T>> {
const response = await this.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 FetchResponse;
return {
data,
response: newResponse,
};
}
/**
* Perform a POST request to a URL with data and optional request options. Will use the cache that is already set in the instance.
* @param {string} url The URL to fetch.
* @param {unknown} data The data to send in the request body.
* @param {Omit<FetchRequestInit, 'method' | 'body'>} options Optional request options (method and body will be set).
* @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
*/
public async post<T = unknown>(
url: string,
data?: unknown,
options?: Omit<FetchRequestInit, "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 this.fetch(url, {
...options,
headers,
body: body as FetchRequestInit["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 FetchResponse;
return {
data: responseData,
response: newResponse,
};
}
/**
* Perform a PATCH request to a URL with data and optional request options. Will use the cache that is already set in the instance.
* @param {string} url The URL to fetch.
* @param {unknown} data The data to send in the request body.
* @param {Omit<FetchRequestInit, 'method' | 'body'>} options Optional request options (method and body will be set).
* @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
*/
public async patch<T = unknown>(
url: string,
data?: unknown,
options?: Omit<FetchRequestInit, "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 this.fetch(url, {
...options,
headers,
body: body as FetchRequestInit["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 FetchResponse;
return {
data: responseData,
response: newResponse,
};
}
}
export const Net = CacheableNet;
export {
type DataResponse,
type FetchOptions,
type FetchRequestInit,
fetch,
type GetResponse,
get,
patch,
post,
type Response as FetchResponse,
} from "./fetch.js";