Skip to content

Commit c4b8a28

Browse files
aaronfrostSanderElias
authored andcommitted
feat(scully): Add replaceFirstRouteParamWithVal util (#123)
* feat(scully): Add replaceFirstRouteParamWithVal util Often people will need to replace the first route param with a value. To prevent them from recreating the split logic and join logic and break logic, this function is a reusable util that people can use. * run prettier on the code, and export the function so that others can use it via npm.
1 parent d8b2405 commit c4b8a28

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

scully/index.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,17 @@ import {HandledRoute} from './routerPlugins/addOptionalRoutesPlugin';
44
import {updateScullyConfig} from './utils/config';
55
import {RouteTypes, ScullyConfig} from './utils/interfacesandenums';
66
import {routeSplit} from './utils/routeSplit';
7+
import {replaceFirstRouteParamWithVal} from './utils/replaceFirstRouteParamWithVal';
78
import {startScully} from './utils/startup';
89

9-
export {startScully, updateScullyConfig, ScullyConfig, registerPlugin, HandledRoute, RouteTypes, routeSplit, configValidator};
10+
export {
11+
startScully,
12+
updateScullyConfig,
13+
ScullyConfig,
14+
registerPlugin,
15+
HandledRoute,
16+
RouteTypes,
17+
routeSplit,
18+
replaceFirstRouteParamWithVal,
19+
configValidator,
20+
};
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* This function replaces the first instance of a route param with the passed value
3+
* @param route - the route from scullyconfig.routes section
4+
* @param val - a string that you will be adding into the parameterized route
5+
*
6+
* replaceFirstRouteParamWithVal('/foo/:bar', '123') // '/foo/123'
7+
* replaceFirstRouteParamWithVal('/foo/:bar/:baz', '123') // '/foo/123/:baz'
8+
*/
9+
export function replaceFirstRouteParamWithVal(route: string, val: string): string {
10+
const pieces: string[] = route.split('/');
11+
for (let i = 0; i < pieces.length; i++) {
12+
if (pieces[i].startsWith(':')) {
13+
pieces[i] = val;
14+
// Once you replace a param, break the loop.
15+
// This allows you to use this on routes with multiple params.
16+
break;
17+
}
18+
}
19+
return pieces.join('/');
20+
}

0 commit comments

Comments
 (0)