Created
August 22, 2023 16:22
-
-
Save devinrhode2/c0545b8715072cb7a7908b125cb4e65c to your computer and use it in GitHub Desktop.
used to monkey patch a `fetch` call inside some javascript framework.
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
// https://stackoverflow.com/questions/43004657/modify-the-url-of-a-new-request-object-in-es6 | |
// used to monkey patch a `fetch` call inside some javascript framework. | |
const serverFnFetch: typeof fetch = function (input, init) { | |
const isRequest = input instanceof Request; | |
const currentUrlObj = new URL( | |
isRequest ? input.url : input, | |
location.href, | |
); | |
const currentUrlWithoutOrigin = currentUrlObj | |
.toString() | |
.replace(currentUrlObj.origin, ''); | |
const newUrl = new URL( | |
currentUrlWithoutOrigin, | |
// `process.env` doesn't work here, env var MUST be prefixed with `VITE_` | |
import.meta.env.VITE_BAC_BASE_URL, | |
); | |
if (!isRequest) { | |
return fetch(newUrl, init); | |
} | |
// Copied from https://github.com/whatwg/fetch/issues/1486#issuecomment-1250073926 | |
const init2 = {}; | |
for (const property in input) { | |
// @ts-expect-error - ugh w/e | |
init2[property] = input[property]; | |
} | |
// @ts-expect-error - ugh w/e | |
init2.duplex = 'half' as const; | |
console.log('init2', init2); | |
const init1 = { | |
// https://stackoverflow.com/questions/43004657/modify-the-url-of-a-new-request-object-in-es6 | |
body: input.body, | |
cache: input.cache, | |
credentials: input.credentials, | |
headers: input.headers, | |
integrity: input.integrity, | |
keepalive: input.keepalive, | |
method: input.method, | |
mode: input.mode, | |
redirect: input.redirect, | |
referrer: input.referrer, | |
referrerPolicy: input.referrerPolicy, | |
signal: input.signal, | |
// duplex: 'half' as const, | |
}; | |
console.log('init1', init1); | |
console.log( | |
'call fetch with init2', | |
fetch(new Request(newUrl, init2), init2), | |
); | |
console.log('call fetch with init1..'); | |
console.log('1. create Request'); | |
let r = new Request(newUrl, init1); | |
console.log('2. call fetch with Request'); | |
let p = fetch(r, init); | |
console.log('3. return promise'); | |
return p; | |
}; | |
globalThis.FrameworksServerFnFetch = serverFnFetch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment