Skip to content

virtualstate/listen

Repository files navigation

@virtualstate/listen

Fetch listener

Support

Node.js supported Deno supported Bun supported

Test Coverage

96.69%25 lines covered 96.69%25 statements covered 95.65%25 functions covered 90.57%25 branches covered

Usage

import { listen } from "@virtualstate/listen";

const { url, close } = await listen(
    event => event.respondWith(new Response("Hello!"))
);

console.log(`Listening on ${url}`);

const response = await fetch(url);
const text = await response.text();
console.log(text);

if (text !== "Hello!") throw new Error("Expected Hello!");

await close();

JSX

import { listen, toResponse, toAsyncString, Fetch } from "@virtualstate/listen";
import { h, descendants, name, properties } from "@virtualstate/focus";

async function *App({ request }) {
    if (request.method === "POST") {
        const body = JSON.parse(
            await toAsyncString(request)
        );
        yield <echo {...body} />
    }
}

const { url, close } = await listen(
    event => event.respondWith(
        toResponse(<App request={event.request} />)
    )
);

const random = Math.random()
const {
    echo: [echo]
} = descendants(
    <Fetch 
        url={url}
        method="POST"
        body={JSON.stringify({
            random
        })}
    />
).group(name);

const body = properties(await echo);
console.log(body);

if (body.random !== random) throw new Error("Expected body to contain random")