PicList/src/main/server/router.ts
2024-03-30 22:46:51 +08:00

38 lines
1.1 KiB
TypeScript

type HttpMethod = 'GET' | 'POST'
class Router {
private router = new Map<string, Map<HttpMethod, {handler: routeHandler, urlparams?: URLSearchParams}>>()
private addRoute (method: HttpMethod, url: string, callback: routeHandler, urlparams?: URLSearchParams): void {
if (!this.router.has(url)) {
this.router.set(url, new Map())
}
this.router.get(url)!.set(method, { handler: callback, urlparams })
}
get (url: string, callback: routeHandler, urlparams?: URLSearchParams): void {
this.addRoute('GET', url, callback, urlparams)
}
post (url: string, callback: routeHandler, urlparams?: URLSearchParams): void {
this.addRoute('POST', url, callback, urlparams)
}
any (url: string, callback: routeHandler, urlparams?: URLSearchParams): void {
this.addRoute('GET', url, callback, urlparams)
this.addRoute('POST', url, callback, urlparams)
}
getHandler (url: string, method: HttpMethod) {
if (this.router.has(url)) {
const methods = this.router.get(url)!
if (methods.has(method)) {
return methods.get(method)
}
}
return null
}
}
export default new Router()