Skip to content

Commit

Permalink
Massive speed up of byPattern
Browse files Browse the repository at this point in the history
pre-construct URLPatterns and don't construct URL for each req
  • Loading branch information
jollytoad committed Dec 5, 2023
1 parent f890504 commit 064abbb
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ Also, many handlers may also accept additional arguments beyond the first

### Argument shunting

Most of the `by*` helpers will pass arguments on as is, or shunt the
arguments along if they want to introduce their own, so for example,
Most of the `by*` helpers will pass arguments on as is, or shunt the arguments
along if they want to introduce their own, so for example,
`byPattern(pattern, handler)` returns a handler with the type:

```ts
Expand Down
9 changes: 5 additions & 4 deletions lib/by_pattern.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@ export function byPattern<A extends unknown[]>(
...args: A
) => Awaitable<Response | null>,
) {
return async (req: Request, ...args: A) => {
const patterns = Array.isArray(pattern) ? pattern : [pattern];
const url = new URL(req.url);
const patterns = Array.isArray(pattern)
? pattern.map(asURLPattern)
: [asURLPattern(pattern)];

return async (req: Request, ...args: A) => {
for (const pattern of patterns) {
const match = asURLPattern(pattern).exec(url);
const match = pattern.exec(req.url);

if (match) {
const res = await handler(req, match, ...args);
Expand Down

0 comments on commit 064abbb

Please sign in to comment.