Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add ability to acess only the query params or the actual route params #744

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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