From 7c81024abcbb68603aeacd4eb52c2bad61a7cfb0 Mon Sep 17 00:00:00 2001 From: Brandon Nason Date: Mon, 6 Dec 2021 08:59:52 -0600 Subject: [PATCH] feat: matchAll Adds a matchAll method that returns an array of matches. --- src/router.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/router.ts b/src/router.ts index 4a1f390..88f5b8a 100644 --- a/src/router.ts +++ b/src/router.ts @@ -151,6 +151,31 @@ export class Router { return null } + /** + * Match the provided method and path against the list of registered routes. + * + * @example + * router.get('/foobar', async () => {}) + * + * const matches = router.matchAll('GET', '/foobar') + * // Call the async function for each match + * for (const match of matches) { + * await match.handler() + * } + */ + public matchAll(method: Method, path: string): RouteMatch[] { + const routes: RouteMatch[] = [] + for (const route of this.routes) { + // Skip immediately if method doesn't match + if (route.method !== method && route.method !== 'ALL') continue + // If method matches try to match path regexp + const matches = route.regexp.exec(path) + if (!matches || !matches.length) continue + routes.push({ ...route, matches, params: keysToParams(matches, route.keys) }) + } + return routes + } + private _push( method: Method | MethodWildcard, path: string,