Skip to content

Commit

Permalink
Add new generateEncodedPath helper
Browse files Browse the repository at this point in the history
- Should be used in place of generatePath
  • Loading branch information
cee-chen committed Feb 2, 2021
1 parent 12e4db9 commit 68a3057
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import '../../../__mocks__/react_router_history.mock';
import { useParams } from 'react-router-dom';

import { encodePathParams, useDecodedParams } from './';
import { encodePathParams, generateEncodedPath, useDecodedParams } from './';

describe('encodePathParams', () => {
it('encodeURIComponent()s all object values', () => {
Expand All @@ -22,6 +22,19 @@ describe('encodePathParams', () => {
});
});

describe('generateEncodedPath', () => {
it('generates a react router path with encoded path parameters', () => {
expect(
generateEncodedPath('/values/:someValue/:anotherValue/new', {
someValue: 'hello world???',
anotherValue: 'test!@#$%^&*[]/|;:"<>~`',
})
).toEqual(
'/values/hello%20world%3F%3F%3F/test!%40%23%24%25%5E%26*%5B%5D%2F%7C%3B%3A%22%3C%3E~%60/new'
);
});
});

describe('useDecodedParams', () => {
it('decodeURIComponent()s all object values from useParams()', () => {
(useParams as jest.Mock).mockReturnValue({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { useParams } from 'react-router-dom';
import { generatePath, useParams } from 'react-router-dom';

export const encodePathParams = (pathParams: Record<string, string | number>) => {
const encodedParams: Record<string, string> = {};
type PathParams = Record<string, string>;

export const encodePathParams = (pathParams: PathParams) => {
const encodedParams: PathParams = {};

Object.entries(pathParams).map(([key, value]) => {
encodedParams[key] = encodeURIComponent(value);
Expand All @@ -16,8 +18,12 @@ export const encodePathParams = (pathParams: Record<string, string | number>) =>
return encodedParams;
};

export const generateEncodedPath = (path: string, pathParams: PathParams) => {
return generatePath(path, encodePathParams(pathParams));
};

export const useDecodedParams = () => {
const decodedParams: Record<string, string> = {};
const decodedParams: PathParams = {};

const params = useParams();
Object.entries(params).map(([key, value]) => {
Expand Down

0 comments on commit 68a3057

Please sign in to comment.