BetterDiscordApp-rauenzi/renderer/src/modules/api/fetch.js

64 lines
1.8 KiB
JavaScript

import Remote from "../../polyfill/remote";
class FetchResponse extends Response {
constructor(options) {
super(options.content, {
headers: new Headers(options.headers),
method: options.method ?? "GET",
body: options.content,
...options
});
this._options = options;
}
get url() {return this._options.url;}
get redirected() {return this._options.redirected;}
}
const convertSignal = signal => {
const listeners = new Set();
signal.addEventListener("abort", () => {
listeners.forEach(l => l());
});
return {
addEventListener(_, listener) {
listeners.add(listener);
}
};
};
export function fetch(url, options = {}) {
return new Promise((resolve, reject) => {
const ctx = Remote.nativeFetch(url, {
...(options.headers && {headers: options.headers instanceof Headers ? Object.fromEntries(options.headers.entries()) : options.headers}),
...(options.body && {body: options.body}),
...(options.method && {method: options.method}),
...(options.signal && {signal: convertSignal(options.signal)})
});
ctx.onError(error => {
reject(error);
});
ctx.onComplete(() => {
try {
const data = ctx.readData();
const req = new FetchResponse({
method: options.method ?? "GET",
status: data.statusCode,
...options,
...data
});
resolve(req);
} catch (error) {
reject(error);
}
});
});
}