Skip to content

Instantly share code, notes, and snippets.

@reggi
Created December 21, 2022 23:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reggi/6bb464619468738a159fa31cec13a5d6 to your computer and use it in GitHub Desktop.
Save reggi/6bb464619468738a159fa31cec13a5d6 to your computer and use it in GitHub Desktop.
class Route {
urlPattern: URLPattern
constructor (
public method: string,
public pathname: string,
public handler: (req: Request) => Promise<Response> | Response
) {
this.urlPattern = new URLPattern({ pathname })
}
}
class Routes {
routes: Route[]
constructor (...routes: Route[]) {
this.routes = routes
}
async match (req: Request): Promise<Response> {
const matches = this.routes.filter(route => {
return route.urlPattern.test(req.url) && route.method === req.method
})
if (matches.length > 1) {
return new Response('internal error, more then one route with the same pathname')
} else if (matches.length === 0) {
return new Response('internal error, not found')
} else {
const response = await matches[0].handler(req)
return response
}
}
}
const application = (database) => {
const elephant = new Route("GET", '/elephant', (req: Request) => {
// access database here database
if (new URL(req.url).searchParams.get('name') === 'dumbo') {
return new Response('dumbo')
}
return new Response('invalid route')
})
const routes = new Routes(
elephant,
)
return routes
}
application({} /** example db pass here */).match(request)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment