|
| 1 | +import { createRouter as _createRouter } from 'radix3' |
| 2 | +import type { Handle } from './handle' |
| 3 | +import type { HTTPMethod } from './types/http' |
| 4 | +import { createError } from './error' |
| 5 | + |
| 6 | +export type RouterMethod = Lowercase<HTTPMethod> |
| 7 | +const RouterMethods: Lowercase<RouterMethod>[] = ['connect', 'delete', 'get', 'head', 'options', 'post', 'put', 'trace'] |
| 8 | + |
| 9 | +export type HandleWithParams = Handle<any, { params: Record<string, string> }> |
| 10 | + |
| 11 | +export type AddWithMethod = (path: string, handle: HandleWithParams) => Router |
| 12 | +export type AddRouteShortcuts = Record<Lowercase<HTTPMethod>, AddWithMethod> |
| 13 | + |
| 14 | +export interface Router extends AddRouteShortcuts { |
| 15 | + add: (path: string, handle: HandleWithParams, method?: RouterMethod | 'all') => Router |
| 16 | + handle: Handle |
| 17 | +} |
| 18 | + |
| 19 | +interface RouteNode { |
| 20 | + handlers: Partial<Record<RouterMethod| 'all', HandleWithParams>> |
| 21 | +} |
| 22 | + |
| 23 | +export function createRouter (): Router { |
| 24 | + const _router = _createRouter<RouteNode>({}) |
| 25 | + const routes: Record<string, RouteNode> = {} |
| 26 | + |
| 27 | + const router: Router = {} as Router |
| 28 | + |
| 29 | + // Utilities to add a new route |
| 30 | + router.add = (path, handle, method = 'all') => { |
| 31 | + let route = routes[path] |
| 32 | + if (!route) { |
| 33 | + routes[path] = route = { handlers: {} } |
| 34 | + _router.insert(path, route) |
| 35 | + } |
| 36 | + route.handlers[method] = handle |
| 37 | + return router |
| 38 | + } |
| 39 | + for (const method of RouterMethods) { |
| 40 | + router[method] = (path, handle) => router.add(path, handle, method) |
| 41 | + } |
| 42 | + |
| 43 | + // Main handle |
| 44 | + router.handle = (req, res) => { |
| 45 | + // Match route |
| 46 | + const matched = _router.lookup(req.url || '/') |
| 47 | + if (!matched) { |
| 48 | + throw createError({ |
| 49 | + statusCode: 404, |
| 50 | + name: 'Not Found', |
| 51 | + statusMessage: `Cannot find any route matching ${req.url || '/'}.` |
| 52 | + }) |
| 53 | + } |
| 54 | + |
| 55 | + // Match method |
| 56 | + const method = (req.method || 'get').toLowerCase() as RouterMethod |
| 57 | + const handler: HandleWithParams | undefined = matched.handlers[method] || matched.handlers.all |
| 58 | + if (!handler) { |
| 59 | + throw createError({ |
| 60 | + statusCode: 405, |
| 61 | + name: 'Method Not Allowed', |
| 62 | + statusMessage: `Method ${method} is not allowed on this route.` |
| 63 | + }) |
| 64 | + } |
| 65 | + |
| 66 | + // Add params |
| 67 | + // @ts-ignore |
| 68 | + req.params = matched.params || {} |
| 69 | + |
| 70 | + // Call handler |
| 71 | + // @ts-ignore |
| 72 | + return handler(req, res) |
| 73 | + } |
| 74 | + |
| 75 | + return router |
| 76 | +} |
0 commit comments