Skip to content

Commit

Permalink
fix: repair builder closure mutating same path reference
Browse files Browse the repository at this point in the history
  • Loading branch information
lukemorales committed Feb 4, 2024
1 parent ee40b00 commit be00799
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/wet-beers-yell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"next-safe-navigation": patch
---

Fix route builder closure mutating same path string
16 changes: 16 additions & 0 deletions src/make-route-builder.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,22 @@ describe('makeRouteBuilder', () => {
});
});
});

describe('when the builder is called multiple times', () => {
it('replaces correctly the path params with the latest value', () => {
const builder = makeRouteBuilder('/organizations/[orgId]', {
params: z.object({
orgId: z.string(),
}),
});

expect(builder({ orgId: 'org_123' })).toBe('/organizations/org_123');

expect(builder({ orgId: 'org_456' })).toBe('/organizations/org_456');

expect(builder({ orgId: 'org_789' })).toBe('/organizations/org_789');
});
});
});

describe('for a path with route params and searchParams', () => {
Expand Down
6 changes: 3 additions & 3 deletions src/make-route-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,8 @@ export function makeRouteBuilder(
path: PathBlueprint,
schemas?: { params?: z.ZodSchema; search?: z.ZodSchema },
): any {
let basePath: string = path;

if (!path.startsWith('/')) {
basePath = `/${path}`;
path = `/${path}`;
}

const hasParamsInPath = /\[\w+\]/g.test(path);
Expand All @@ -115,6 +113,8 @@ export function makeRouteBuilder(
}

const routeBuilder: RouteBuilder<any, any> = (options) => {
let basePath: string = path;

const { search = {}, ...params } = options ?? {};

for (const [param, value] of Object.entries(params)) {
Expand Down

0 comments on commit be00799

Please sign in to comment.