Skip to content

Instantly share code, notes, and snippets.

@ernestofreyreg
Last active February 9, 2020 00:18
Show Gist options
  • Save ernestofreyreg/710efed39dc82acac1f9f18041b5dc30 to your computer and use it in GitHub Desktop.
Save ernestofreyreg/710efed39dc82acac1f9f18041b5dc30 to your computer and use it in GitHub Desktop.
import { isValidJwt } from './jwt'
import { KVNamespace } from '@cloudflare/workers-types'
declare const TODOS: KVNamespace
async function handleGETRequests (request: Request, token: any) {
const url = new URL(request.url)
switch (url.pathname) {
case '/status':
return new Response(JSON.stringify({ hello: 'world' }))
case '/todos': {
const todos = await TODOS.get(token.sub)
return new Response(todos || '[]', {
status: 200,
headers: { 'Content-Type': 'application/json' }
})
}
}
return new Response(null, { status: 404 })
}
async function handlePOSTRequests (request: Request, token: any) {
const url = new URL(request.url)
switch (url.pathname) {
case '/todos': {
const payload = await request.json()
const todos: any = (await TODOS.get(token.sub, 'json')) || []
todos.push(payload.todo)
await TODOS.put(token.sub, JSON.stringify(todos))
return new Response(null, { status: 204 })
}
}
return new Response(null, { status: 400 })
}
async function handleDELETERequests (request: Request, token: any) {
const url = new URL(request.url)
switch (url.pathname) {
case '/todos': {
const payload = await request.json()
const todos: any = (await TODOS.get(token.sub, 'json')) || []
const index = payload.index
if (todos.length > 0 && index >= 0 && index < todos.length) {
await TODOS.put(
token.sub,
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) {
const { valid, payload } = await isValidJwt(request)
if (!valid) {
return new Response(null, { status: 403 })
}
if (request.method === 'POST') {
return handlePOSTRequests(request, payload)
}
if (request.method === 'DELETE') {
return handleDELETERequests(request, payload)
}
return handleGETRequests(request, payload)
}
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