Skip to content

Instantly share code, notes, and snippets.

@ernestofreyreg
Last active February 9, 2020 00:19
Show Gist options
  • Save ernestofreyreg/0c29c7b36fdae71007c9ac10ab984066 to your computer and use it in GitHub Desktop.
Save ernestofreyreg/0c29c7b36fdae71007c9ac10ab984066 to your computer and use it in GitHub Desktop.
import { KVNamespace } from '@cloudflare/workers-types'
declare const TODOS: KVNamespace
async function handleGETRequests (request: Request) {
const url = new URL(request.url)
switch (url.pathname) {
case '/status':
return new Response(JSON.stringify({ hello: 'world' }))
case '/todos': {
const todos: any = await TODOS.get(url.searchParams.get('user'))
return new Response(todos || '[]', {
status: 200,
headers: { 'Content-Type': 'application/json' }
})
}
}
return new Response(null, { status: 404 })
}
async function handlePOSTRequests (request: Request) {
const url = new URL(request.url)
switch (url.pathname) {
case '/todos': {
const payload = await request.json()
const todos: any = (await TODOS.get(payload.user, 'json')) || []
todos.push(payload.todo)
await TODOS.put(payload.user, JSON.stringify(todos))
return new Response(null, { status: 204 })
}
}
return new Response(null, { status: 400 })
}
async function handleDELETERequests (request: Request) {
const url = new URL(request.url)
switch (url.pathname) {
case '/todos': {
const payload = await request.json()
const todos = (await TODOS.get(payload.user, 'json')) || []
const index = payload.index
if (todos.length > 0 && index >= 0 && index < todos.length) {
await TODOS.put(
payload.user,
JSON.stringify(todos.slice(0, index).concat(todos.slice(index + 1)))
)
}
return new Response(null, { status: 204 })
}
}
return new Response(null, { status: 400 })
}
async function handleRequest (request: Request) {
if (request.method === 'POST') {
return handlePOSTRequests(request)
}
if (request.method === 'DELETE') {
return handleDELETERequests(request)
}
return handleGETRequests(request)
}
function handler (event: FetchEvent) {
event.respondWith(handleRequest(event.request))
}
addEventListener('fetch', handler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment