Skip to content

Commit

Permalink
Reverse execution order of Pages Functions middlewares (#217)
Browse files Browse the repository at this point in the history
* Sort root requests, /, last

* Reverse execution order of Pages Functions middlewares
  • Loading branch information
GregBrimble authored Jan 7, 2022
1 parent 79d0f2d commit 777f4d5
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/fuzzy-ads-rush.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wrangler": patch
---

Reverse execution order of Pages Functions middlewares
9 changes: 8 additions & 1 deletion packages/wrangler/pages/functions/filepath-routing.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { compareRoutes } from "./filepath-routing";

describe("compareRoutes()", () => {
test("routes / last", () => {
expect(compareRoutes("/", "/foo")).toBeGreaterThanOrEqual(1);
expect(compareRoutes("/", "/:foo")).toBeGreaterThanOrEqual(1);
expect(compareRoutes("/", "/:foo*")).toBeGreaterThanOrEqual(1);
});

test("routes with fewer segments come after those with more segments", () => {
expect(compareRoutes("/foo", "/foo/bar")).toBe(1);
expect(compareRoutes("/foo", "/foo/bar")).toBeGreaterThanOrEqual(1);
expect(compareRoutes("/foo", "/foo/bar/cat")).toBeGreaterThanOrEqual(1);
});

test("routes with wildcard segments come after those without", () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/wrangler/pages/functions/filepath-routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ export function compareRoutes(a: string, b: string) {
method = null;
}

const segments = segmentedPath.slice(1).split("/");
const segments = segmentedPath.slice(1).split("/").filter(Boolean);
return [method, segments];
}

Expand Down
4 changes: 2 additions & 2 deletions packages/wrangler/pages/functions/template-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ type WorkerContext = {
function* executeRequest(request: Request, env: Env) {
const requestPath = new URL(request.url).pathname;

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

0 comments on commit 777f4d5

Please sign in to comment.