Skip to content

Instantly share code, notes, and snippets.

@jahands
Created June 7, 2020 15:54
Show Gist options
  • Save jahands/0fe653e3a969900b0f54f05968256c94 to your computer and use it in GitHub Desktop.
Save jahands/0fe653e3a969900b0f54f05968256c94 to your computer and use it in GitHub Desktop.
import { Router, Method, Params } from 'tiny-request-router'
// Let the router know that handlers are async functions returning a Response
type Handler = (params: Params, request: Request) => Promise<Response>
const router = new Router<Handler>()
router.get('/upload/:name', async (params: Params, request: Request) => upload(params, request))
export async function handle(event: FetchEvent): Promise<Response> {
let request = event.request
let url = new URL(request.url)
const match = router.match(request.method as Method, url.pathname)
if (match) {
const response = match.handler(match.params, request)
return response
}
return new Response('not found', { status: 404 })
}
async function upload(params: Params, request: Request): Promise<Response> {
let url = new URL(request.url)
return new Response(`Hello ${params.name}, ${url.searchParams.get('bob')}`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment