Last active
September 6, 2019 22:25
-
-
Save MarkTiedemann/7f283d43b34ebc320d6dfee480dc6053 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let http = require("http") | |
let html = String.raw | |
let cms = { | |
title: "My Title", | |
text: "My text" | |
} | |
function site(editable) { | |
let edit = editable ? ` contenteditable="true"` : "" | |
let save = edit ? html` | |
<script> | |
function save() { | |
let body = JSON.stringify({ | |
title: document.getElementById("title").textContent, | |
text: document.getElementById("text").textContent | |
}) | |
fetch("/config", { method: "PUT", body }) | |
} | |
</script> | |
<button onclick="save()">Save</button>` : "" | |
return html`<!DOCTYPE html>${save} | |
<h1 id="title"${edit}>${cms.title}</h1> | |
<p id="text"${edit}>${cms.text}</p> | |
` | |
} | |
http.createServer(async function(req, res) { | |
if (req.url === "/config") { | |
try { | |
let buf = [] | |
for await (let chunk of req) buf.push(chunk) | |
let body = Buffer.concat(buf).toString() | |
let json = JSON.parse(body) | |
cms.title = json.title | |
cms.text = json.text | |
res.writeHead(200) | |
res.end() | |
} catch { | |
res.writeHead(400) | |
res.end() | |
} | |
} else { | |
res.writeHead(200, { "content-type": "text/html" }) | |
res.end(site(req.url === "/edit")) | |
} | |
}).listen(80) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment