This commit is contained in:
2022-07-21 03:28:35 +00:00
parent d7c883d6df
commit 51b34b0e1d
30103 changed files with 4152204 additions and 23 deletions
+46
View File
@@ -0,0 +1,46 @@
import {
Body as NodeBody,
Headers as NodeHeaders,
Request as NodeRequest,
Response as NodeResponse,
RequestInit as NodeRequestInit
} from "node-fetch";
declare namespace unfetch {
export type IsomorphicHeaders = Headers | NodeHeaders;
export type IsomorphicBody = Body | NodeBody;
export type IsomorphicResponse = Response | NodeResponse;
export type IsomorphicRequest = Request | NodeRequest;
export type IsomorphicRequestInit = RequestInit | NodeRequestInit;
}
type UnfetchResponse = {
ok: boolean,
statusText: string,
status: number,
url: string,
text: () => Promise<string>,
json: () => Promise<any>,
blob: () => Promise<Blob>,
clone: () => UnfetchResponse,
headers: {
keys: () => string[],
entries: () => Array<[string, string]>,
get: (key: string) => string | undefined,
has: (key: string) => boolean,
}
}
type Unfetch = (
url: string,
options?: {
method?: string,
headers?: Record<string, string>,
credentials?: 'include' | 'omit',
body?: Parameters<XMLHttpRequest["send"]>[0]
}
) => Promise<UnfetchResponse>
declare const unfetch: Unfetch;
export default unfetch;
+47
View File
@@ -0,0 +1,47 @@
export default function(url, options) {
options = options || {};
return new Promise( (resolve, reject) => {
const request = new XMLHttpRequest();
const keys = [];
const all = [];
const headers = {};
const response = () => ({
ok: (request.status/100|0) == 2, // 200-299
statusText: request.statusText,
status: request.status,
url: request.responseURL,
text: () => Promise.resolve(request.responseText),
json: () => Promise.resolve(request.responseText).then(JSON.parse),
blob: () => Promise.resolve(new Blob([request.response])),
clone: response,
headers: {
keys: () => keys,
entries: () => all,
get: n => headers[n.toLowerCase()],
has: n => n.toLowerCase() in headers
}
});
request.open(options.method || 'get', url, true);
request.onload = () => {
request.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm, (m, key, value) => {
keys.push(key = key.toLowerCase());
all.push([key, value]);
headers[key] = headers[key] ? `${headers[key]},${value}` : value;
});
resolve(response());
};
request.onerror = reject;
request.withCredentials = options.credentials=='include';
for (const i in options.headers) {
request.setRequestHeader(i, options.headers[i]);
}
request.send(options.body || null);
});
}