Fetch API implementation for QuickJS runtime
npm install @ricsam/quickjs-fetchFetch API and HTTP server handler for QuickJS runtime.
> Note: This is a low-level package. For most use cases, use @ricsam/quickjs-runtime with createRuntime() instead.
``bash`
bun add @ricsam/quickjs-fetch
`typescript
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);
},
});
- fetch, Request, Response, HeadersFormData
- , AbortController, AbortSignalserve
- (HTTP server handler)
`javascript
// 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"));
`
Register a server handler in QuickJS and dispatch requests from the host:
`typescript
// 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");
}
``