Skip to content

Instantly share code, notes, and snippets.

@tonylampada
Created September 18, 2023 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonylampada/192442087b3830d4c7e7698e0d3daaab to your computer and use it in GitHub Desktop.
Save tonylampada/192442087b3830d4c7e7698e0d3daaab to your computer and use it in GitHub Desktop.
// web framework
function webapp() {
return {
handlers: {},
addRoute(route, fn){
this.handlers[route] = fn;
},
exec(route, params){
const handler = this.handlers[route];
if (!handler) {
return {status: 404, body: `route not found: ${route}`}
}
return new Promise((resolve) => {
handler(params, {send: ({status, body}) => {
status = status || 200;
body = body || "OK"
resolve({status, body});
}}).catch(err => {
console.error(`[REQUEST ERROR] - ${route} with params ${params}`, err)
resolve({status: 500, body: "unknown error"})
})
})
}
}
}
function sleep(ms) {
// async pause, for dramatic purposes
return new Promise((r) => setTimeout(r, ms));
}
// backend services
const services = {
loadFooFromDatabase(id) {
return sleep(300).then(() => {
return {id, name: "foo"};
})
},
saveFooToStorage(foo, filename) {
return sleep(300).then(() => {
const fooData = {id: foo.id, Name: foo.Name, size: foo.Name.length};
console.log(`storage pretend save: ${JSON.stringify(fooData)}`)
const storageId = parseInt(Math.random() * 1E10);
return storageId;
})
},
scheduleFooTransfer(storageId) {
return sleep(300).then(() => {
console.log(`fake pubsub call with storageId ${storageId}`)
const messageId = parseInt(Math.random() * 1E10);
return messageId
})
}
}
// my app
const myapp = webapp();
myapp.addRoute('/save/foo3', savefoo3)
function savefoo3(params, res) {
const {id} = params;
return services.loadFooFromDatabase(id).then(foo => {
return services.saveFooToStorage(foo, `/path/to/foo/${foo.id}`)
}).then(storageId => {
return services.scheduleFooTransfer(storageId)
}).then(messageId => {
console.log(`finished processing foo ${id}. MessageID = ${messageId}`)
res.send({status: 200, body: `OK - foo processed ${id}`})
})
}
module.exports = myapp
// let r3;
// myapp.exec('/save/foo3', {id: 3}).then(r => {r3 = r})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment