Skip to content

Commit 777f4d5

Browse files
authored
Reverse execution order of Pages Functions middlewares (#217)
* Sort root requests, /, last * Reverse execution order of Pages Functions middlewares
1 parent 79d0f2d commit 777f4d5

File tree

4 files changed

+16
-4
lines changed

4 files changed

+16
-4
lines changed

.changeset/fuzzy-ads-rush.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"wrangler": patch
3+
---
4+
5+
Reverse execution order of Pages Functions middlewares

packages/wrangler/pages/functions/filepath-routing.test.ts

+8-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
11
import { compareRoutes } from "./filepath-routing";
22

33
describe("compareRoutes()", () => {
4+
test("routes / last", () => {
5+
expect(compareRoutes("/", "/foo")).toBeGreaterThanOrEqual(1);
6+
expect(compareRoutes("/", "/:foo")).toBeGreaterThanOrEqual(1);
7+
expect(compareRoutes("/", "/:foo*")).toBeGreaterThanOrEqual(1);
8+
});
9+
410
test("routes with fewer segments come after those with more segments", () => {
5-
expect(compareRoutes("/foo", "/foo/bar")).toBe(1);
11+
expect(compareRoutes("/foo", "/foo/bar")).toBeGreaterThanOrEqual(1);
12+
expect(compareRoutes("/foo", "/foo/bar/cat")).toBeGreaterThanOrEqual(1);
613
});
714

815
test("routes with wildcard segments come after those without", () => {

packages/wrangler/pages/functions/filepath-routing.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ export function compareRoutes(a: string, b: string) {
162162
method = null;
163163
}
164164

165-
const segments = segmentedPath.slice(1).split("/");
165+
const segments = segmentedPath.slice(1).split("/").filter(Boolean);
166166
return [method, segments];
167167
}
168168

packages/wrangler/pages/functions/template-worker.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,8 @@ type WorkerContext = {
4343
function* executeRequest(request: Request, env: Env) {
4444
const requestPath = new URL(request.url).pathname;
4545

46-
// First, iterate through the routes and execute "middlewares" on partial route matches
47-
for (const route of routes) {
46+
// First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
47+
for (const route of [...routes].reverse()) {
4848
if (
4949
route.methods.length &&
5050
!route.methods.includes(request.method as HTTPMethod)

0 commit comments

Comments
 (0)