Published
Edited
Jun 9, 2021
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
//Example of using an dynamically imported notebooks as a backend.. to properly use this, we will create a collection of notebooks that take some inputs and resolve to a response cell!
//here we use promise so we only capture the first fulfileld value of a cell.. the other one (evaluateCell) uses a generator! But we can only respond to http once, so..

//Also this function uses a hack that lets this work even in a background tab on your browser.. i.e. no requestanimationframe..
evaluateCellOnce(
"sum",
"https://api.observablehq.com/@observablehq/reactive-dataflow.js?v=3",
{ a: 4, b: 3 }
)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
socket = {
let socket = io("http://localhost:5555"); //replace with your url!
socket.on('notebook-proxy', d => {
mutable req_latest = d; //we can inspect the request data here easily!
mutable req_history.push(d); // we can even use the earlier req data to use it cleverly in the future responses..
handler(d).then(resp => {
socket.emit('notebook-proxy', {
id: d.id,
data: resp
});
});
});
invalidation.then(() => {
socket.off("notebook-proxy");
});
return socket;
}
Insert cell
Insert cell
handler = async d => {
var req = d.body;

//do your routing here..
//iterate as often as needed, your mock server is always live to your most recent keystroke!
//
if (d.url == "/test") {
return evaluateCellOnce(req.cell, req.notebook, req.inject);
} else {
return {
title: "This is a mock json!!"
};
}
}
Insert cell
Insert cell
test = fetch("http://localhost:5555/test", {
method: "post",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
cell: "sum",
notebook:
"https://api.observablehq.com/@observablehq/reactive-dataflow.js?v=3",
inject: { a: 1412, b: 2123 }
})
}).then(d => d.json())

//This cell is frontend making a request! The rest of the notebook is basically the backend that responds to it!
//note that there is no route on the backend.. we jsut get the raw details forwarded and it's up to us to use it, this means once we start the proxy ndoejs server, we simply do all our work from the browser!
Insert cell
example = fetch("http://localhost:5555/example123").then(d => d.json())

//This cell is frontend making a request! The rest of the notebook is basically the backend that responds to it!
//note that there is no route on the backend.. we jsut get the raw details forwarded and it's up to us to use it, this means once we start the proxy ndoejs server, we simply do all our work from the browser!
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