Skip to content

Instantly share code, notes, and snippets.

@o-t-w
Last active November 23, 2018 16:20
Show Gist options
  • Save o-t-w/cd8b692c127016a5d0f1f53fb8846160 to your computer and use it in GitHub Desktop.
Save o-t-w/cd8b692c127016a5d0f1f53fb8846160 to your computer and use it in GitHub Desktop.
Getting values from a Cloudflare KV store and from a header and displaying them inside a template.
const basicHTML = require('basichtml');
basicHTML.init();
document.documentElement.setAttribute('lang', 'en');
const {bind} = require('hyperhtml');
addEventListener('fetch', event => {
event.respondWith(responder(event.request))
});
async function responder(request) {
const response = await fetch(request);
const contentType = response.headers.get('Content-Type');
if (!contentType.startsWith('text/html')) {
return response;
}
const valFromDB = await db.get('first-key');
const country = request.headers.get('Cf-Ipcountry');
const model = {
index: {
country: country,
message: valFromDB
}
};
const render = {
index: model => bind(document.documentElement)
`
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="icon"
type="image/x-icon"
href="favicon.ico">
<title>Hello World!</title>
<link rel="preload" href="RocherColorGX.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 spellcheck="false" contenteditable="true" id="main-title">${model.message}</h1>
<h2>${model.country}</h2>
</body>`
};
const serve = type => render[type](model[type]).parentNode.toString();
let customResponse = new Response(
serve('index'),
{
status: 200,
statusText: 'OK',
headers: {'content-type': 'text/html;charset=utf-8'}
}
);
return customResponse;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment