@ricsam/quickjs-fetch
v0.2.20
Published
Fetch API implementation for QuickJS runtime
Maintainers
Readme
@ricsam/quickjs-fetch
Fetch API and HTTP server handler for QuickJS runtime.
Note: This is a low-level package. For most use cases, use
@ricsam/quickjs-runtimewithcreateRuntime()instead.
Installation
bun add @ricsam/quickjs-fetchSetup
import { setupFetch } from "@ricsam/quickjs-fetch";
const handle = setupFetch(context, {
onFetch: async (request) => {
// Handle outbound fetch() calls from QuickJS
console.log(`Fetching: ${request.url}`);
return fetch(request);
},
});Injected Globals
fetch,Request,Response,HeadersFormData,AbortController,AbortSignalserve(HTTP server handler)
Usage in QuickJS
// Outbound fetch
const response = await fetch("https://api.example.com/data");
const data = await response.json();
// Request/Response
const request = new Request("https://example.com", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "test" }),
});
const response = new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
// Static methods
Response.json({ message: "hello" });
Response.redirect("https://example.com", 302);
// AbortController
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
await fetch(url, { signal: controller.signal });
// FormData
const formData = new FormData();
formData.append("name", "John");
formData.append("file", new File(["content"], "file.txt"));HTTP Server
Register a server handler in QuickJS and dispatch requests from the host:
// In QuickJS
context.evalCode(`
serve({
fetch(request, server) {
const url = new URL(request.url);
if (url.pathname === "/ws") {
if (server.upgrade(request, { data: { userId: "123" } })) {
return new Response(null, { status: 101 });
}
}
return Response.json({ path: url.pathname });
},
websocket: {
open(ws) {
console.log("Connected:", ws.data.userId);
},
message(ws, message) {
ws.send("Echo: " + message);
},
close(ws, code, reason) {
console.log("Closed:", code, reason);
}
}
});
`);
// From host - dispatch HTTP request
const response = await handle.dispatchRequest(
new Request("http://localhost/api/users")
);
// Check for WebSocket upgrade
const upgrade = handle.getUpgradeRequest();
if (upgrade?.requested) {
// connectionId is generated by QuickJS in server.upgrade()
// User data stays within QuickJS (no marshalling of complex objects)
const { connectionId } = upgrade;
handle.dispatchWebSocketOpen(connectionId);
// Listen for outgoing messages
handle.onWebSocketCommand((command) => {
if (command.type === "message") {
// Send to actual WebSocket client
}
});
// Forward incoming messages
handle.dispatchWebSocketMessage(connectionId, "Hello from client");
}