Created
July 19, 2020 21:24
-
-
Save reaktivo/3b933849720e66266d9886035b31558c to your computer and use it in GitHub Desktop.
Simple ponyfill for QuickJS
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 * as os from 'os'; | |
import * as std from 'std'; | |
function mapToFetchResponse(fullResponse) { | |
const { | |
responseHeaders, | |
status, | |
response, | |
} = fullResponse; | |
const headerEntries = responseHeaders.trim().split('\n').map(line => { | |
const [key, value] = line.split(':'); | |
return [key.trim(), value.trim()]; | |
}); | |
return { | |
status, | |
headers: Object.fromEntries(headerEntries), | |
ok: status >= 200 && status <= 299, | |
async json() { | |
return JSON.parse(response) | |
}, | |
async text() { | |
return response; | |
} | |
} | |
} | |
export default async function fetch(url, options) { | |
if (options) { | |
throw new Error('Fetch options not supported'); | |
} | |
return new Promise((resolve, reject) => { | |
const worker = new os.Worker(` | |
import * as os from 'os'; | |
import * as std from 'std'; | |
const parent = os.Worker.parent; | |
parent.onmessage = (event) => { | |
const [url, options] = event.data; | |
const data = std.urlGet(url, { full: true }); | |
parent.postMessage(data); | |
} | |
`); | |
worker.onmessage = (event) => { | |
if (event.data.status) { | |
resolve(mapToFetchResponse(event.data)); | |
} else { | |
reject('Request failed'); | |
} | |
worker.onmessage = null; | |
} | |
worker.postMessage([url, options]); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment