Skip to content

Commit

Permalink
Merge pull request #744 from peter-emad99/add-queryParams-and-routePa…
Browse files Browse the repository at this point in the history
…rams-methods

add ability to acess only the query params or the actual route params
  • Loading branch information
bakerkretzmar authored Jul 21, 2024
2 parents a72a346 + 32c8a5a commit 713e466
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/js/Router.js
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,14 @@ export default class Router extends String {
return { ...params, ...query };
}

get routeParams() {
return this._unresolve().params;
}

get queryParams() {
return this._unresolve().query;
}

/**
* Check whether the given route exists.
*
Expand Down
2 changes: 2 additions & 0 deletions src/js/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,8 @@ interface Router {
current(): RouteName | undefined;
current<T extends RouteName>(name: T, params?: ParameterValue | RouteParams<T>): boolean;
get params(): Record<string, string>;
get routeParams(): Record<string, string>;
get queryParams(): Record<string, string>;
has<T extends RouteName>(name: T): boolean;
}

Expand Down
23 changes: 23 additions & 0 deletions tests/js/route.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,29 @@ describe('route()', () => {
});
});

test('can extract only route parameters from the current URL', () => {
global.window.location.href = 'https://ziggy.dev/posts/1?post=2&foo=bar';
global.window.location.host = 'ziggy.dev';
global.window.location.pathname = '/posts/1';
global.window.location.search = '?post=2&foo=bar';

// Query param overwrites route param
expect(route().params).toStrictEqual({ post: '2', foo: 'bar' });

// Can't use strict equality, route().routeParams has a null prototype
expect(route().routeParams).toEqual({ post: '1' });
expect(JSON.stringify(route().routeParams)).toBe(JSON.stringify({ post: '1' }));
});

test('can extract only query parameters from the current URL', () => {
global.window.location.href = 'https://ziggy.dev/posts/1?post=2&foo=bar';
global.window.location.host = 'ziggy.dev';
global.window.location.pathname = '/posts/1';
global.window.location.search = '?post=2&foo=bar';

expect(route().queryParams).toStrictEqual({ post: '2', foo: 'bar' });
});

test("can append 'extra' string/number parameter to query", () => {
// 'posts.index' has no parameters
expect(route('posts.index', 'extra')).toBe('https://ziggy.dev/posts?extra=');
Expand Down

0 comments on commit 713e466

Please sign in to comment.