Skip to content

Instantly share code, notes, and snippets.

@bradjones1
Created February 15, 2022 03:10
Show Gist options
  • Save bradjones1/dae3207aa7dce6eb508cfec56a76ae99 to your computer and use it in GitHub Desktop.
Save bradjones1/dae3207aa7dce6eb508cfec56a76ae99 to your computer and use it in GitHub Desktop.
Fetch shim for Matrix JS SDK
import stringify from './querystring';
// Adjusted from http-api.ts to use fetch.
type RequestCallback = (err?: Error, response?: Response, body?: string) => void;
export default class RequestWrapper {
static fetchFn: typeof fetch;
static getRequestFn() {
let fn = (options, callbackFn: RequestCallback, signal) => {
RequestWrapper.fetchFn(
// This is brought over from the SDK's use of request.
options.uri + '?' + stringify(options.qs, options.qsStringifyOptions),
{...options, signal}
).then(async (response) => {
callbackFn(null, response, await response.text());
})
.catch(err => {
if (err.name !== 'AbortError') {
throw Object.assign(new Error(
err?.description || 'Error making request to Matrix API.'
), {raw: err});
}
});
};
return (options, callback) => {
const abortController = new AbortController();
fn.prototype.abort = abortController.abort.bind(abortController);
return new fn(options, callback, abortController.signal)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment