Created
February 15, 2022 03:10
-
-
Save bradjones1/dae3207aa7dce6eb508cfec56a76ae99 to your computer and use it in GitHub Desktop.
Fetch shim for Matrix JS SDK
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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