add support for URLs without a leading slash

This commit is contained in:
Jacob Overgaard
2024-03-11 16:12:55 +01:00
parent d7d1c7925e
commit 638c1139f9
2 changed files with 6 additions and 4 deletions

View File

@@ -8,8 +8,10 @@ describe('createRoutePathBuilder', () => {
});
it('should return a function that builds a route path with parameters', () => {
const buildPath = createRoutePathBuilder('test/:param1/path/:param2');
expect(buildPath({ param1: 'value1', param2: 'value2' })).to.eq('/test/value1/path/value2/');
const buildPath = createRoutePathBuilder(':param0/test/:param1/path/:param2');
expect(buildPath({ param0: 'value0', param1: 'value1', param2: 'value2' })).to.eq(
'/value0/test/value1/path/value2/',
);
});
it('should convert number parameters to strings', () => {

View File

@@ -1,7 +1,7 @@
/* eslint-disable */
import { stripSlash } from '@umbraco-cms/backoffice/external/router-slot'; // This must only include the util to avoid side effects of registering the route element.
const PARAM_IDENTIFIER = /\/:([^\/]+)/g;
const PARAM_IDENTIFIER = /:([^\/]+)/g;
export function createRoutePathBuilder(path: string) {
return (params: { [key: string]: string | number | { toString: () => string } } | null) => {
@@ -11,7 +11,7 @@ export function createRoutePathBuilder(path: string) {
params
? path.replace(PARAM_IDENTIFIER, (_substring: string, ...args: string[]) => {
// Replace the parameter with the value from the params object or the parameter name if it doesn't exist (args[0] is the parameter name without the colon)
return '/' + (typeof params[args[0]] !== 'undefined' ? params[args[0]].toString() : `:${args[0]}`);
return typeof params[args[0]] !== 'undefined' ? params[args[0]].toString() : `:${args[0]}`;
})
: path,
) +