Skip to content

Instantly share code, notes, and snippets.

@jonashaag
Created August 23, 2022 11:12
Show Gist options
  • Save jonashaag/ba02addf16ee5ce6181c36b0440ccdd2 to your computer and use it in GitHub Desktop.
Save jonashaag/ba02addf16ee5ce6181c36b0440ccdd2 to your computer and use it in GitHub Desktop.
Cloudflare Workers simple key value database
declare const KV: KVNamespace
addEventListener('fetch', event => event.respondWith(handleRequest(event.request)))
const handleRequest = async (request: Request): Promise<Response> => {
if (!auth(request)) {
return new Response('Forbidden', { status: 403 })
}
const key = new URL(request.url).pathname.substr(1)
if (request.method === 'PUT') {
const data = await request.text()
await KV.put(key, JSON.stringify({data: data}))
return new Response()
}
if (request.method === 'GET') {
const res = await KV.get(key)
if (res) {
return new Response(JSON.parse(res).data)
} else {
return new Response('', {status: 404})
}
}
return new Response('', {status: 400})
}
const auth = (request: Request) : boolean => {
const Authorization = request.headers.get('Authorization') || ''
const [scheme, encoded] = Authorization.split(' ')
if (!encoded || scheme !== 'Basic') {
return false
}
const buffer = Uint8Array.from(atob(encoded), character => character.charCodeAt(0))
const decoded = new TextDecoder().decode(buffer).normalize()
const index = decoded.indexOf(':')
if (index === -1 || /[\0-\x1F\x7F]/.test(decoded)) {
return false
}
const auth = {
user: decoded.substring(0, index),
pass: decoded.substring(index + 1),
}
return auth.user === 'secret' && auth.pass === 'secret'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment