Published unlisted
Edited
Feb 4, 2022
Insert cell
Insert cell
viewof square = serveFunction((x) => {
return x * x;
})
Insert cell
square(12)
Insert cell
serveFunction = (fn, { name = "default" } = {}) => {
const server = endpoint(name || "default", async (req, res) => {
const args = req.query.args ? JSON.parse(req.query.args) : [];
const response = await fn(...args);
if (!response) res.status(204).end();
else res.json(response);
});

const client = htl.html`<span>${server}`;
client.value = async (...args) => {
const response = await fetch(
server.href + "?args=" + encodeURIComponent(JSON.stringify(args))
);
if (response.status === 200) {
return response.json();
} else if (response.status === 204) {
return undefined;
} else {
throw new Error(`Status: ${response.status}, ${await response.text()}`);
}
};
return client;
}
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more