Created
December 21, 2022 23:55
-
-
Save reggi/6bb464619468738a159fa31cec13a5d6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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