2024-03-30 10:46:51 -04:00
|
|
|
type HttpMethod = 'GET' | 'POST'
|
|
|
|
|
2019-12-31 10:50:19 -05:00
|
|
|
class Router {
|
2024-03-30 10:46:51 -04:00
|
|
|
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 })
|
|
|
|
}
|
2019-12-31 10:50:19 -05:00
|
|
|
|
2023-09-06 11:40:50 -04:00
|
|
|
get (url: string, callback: routeHandler, urlparams?: URLSearchParams): void {
|
2024-03-30 10:46:51 -04:00
|
|
|
this.addRoute('GET', url, callback, urlparams)
|
2019-12-31 10:50:19 -05:00
|
|
|
}
|
2022-01-04 10:40:28 -05:00
|
|
|
|
2023-09-06 11:40:50 -04:00
|
|
|
post (url: string, callback: routeHandler, urlparams?: URLSearchParams): void {
|
2024-03-30 10:46:51 -04:00
|
|
|
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)
|
2019-12-31 10:50:19 -05:00
|
|
|
}
|
|
|
|
|
2024-03-30 10:46:51 -04:00
|
|
|
getHandler (url: string, method: HttpMethod) {
|
2019-12-31 10:50:19 -05:00
|
|
|
if (this.router.has(url)) {
|
2024-03-30 10:46:51 -04:00
|
|
|
const methods = this.router.get(url)!
|
|
|
|
if (methods.has(method)) {
|
|
|
|
return methods.get(method)
|
|
|
|
}
|
2019-12-31 10:50:19 -05:00
|
|
|
}
|
2024-03-30 10:46:51 -04:00
|
|
|
return null
|
2019-12-31 10:50:19 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default new Router()
|