Writing code
FUNCTION
@skmtc/lang-typescript 0.19.1toPathParams
Converts OpenAPI path parameters to React Router path parameter syntax.
This utility function transforms OpenAPI path syntax (using curly braces) into React Router path parameter syntax (using colon prefix). It's essential for generating React Router route definitions and other routing configurations that need to match URL parameters.
The function performs a simple but crucial transformation that enables OpenAPI-defined paths to be used directly in React Router route definitions, maintaining the same parameter names while adapting the syntax.
Signature
import { toPathParams } from '@skmtc/lang-typescript'
toPathParams(path: string): stringParameters
path, string required
OpenAPI path string with {parameter} syntax
Basic path parameter conversion
import { toPathParams } from '@skmtc/lang-typescript';
const routePath = toPathParams('/users/{id}/posts/{postId}');
console.log(routePath); // '/users/:id/posts/:postId'React Router route generation
import { Routes, Route } from 'react-router-dom';
const apiPaths = [
'/users/{id}',
'/users/{id}/posts/{postId}',
'/organizations/{orgId}/members/{userId}'
];
const routePaths = apiPaths.map(toPathParams);
// [
// '/users/:id',
// '/users/:id/posts/:postId',
// '/organizations/:orgId/members/:userId'
// ]
function App() {
return (
<Routes>
{routePaths.map(path => (
<Route key={path} path={path} element={<DetailView />} />
))}
</Routes>
);
}Express.js route generation
import express from 'express';
class RouteGenerator {
generateExpressRoutes(openApiPaths: string[]) {
const router = express.Router();
openApiPaths.forEach(path => {
const expressPath = toPathParams(path);
router.get(expressPath, (req, res) => {
// Handler logic using req.params
res.json({ path: expressPath, params: req.params });
});
});
return router;
}
}
const generator = new RouteGenerator();
const router = generator.generateExpressRoutes([
'/api/users/{userId}',
'/api/users/{userId}/orders/{orderId}'
]);
// Generates routes for:
// '/api/users/:userId'
// '/api/users/:userId/orders/:orderId'Route configuration generation
interface RouteConfig {
path: string;
component: string;
exact?: boolean;
}
function generateRouteConfigs(apiEndpoints: Array<{path: string, component: string}>): RouteConfig[] {
return apiEndpoints.map(endpoint => ({
path: toPathParams(endpoint.path),
component: endpoint.component,
exact: true
}));
}
const routeConfigs = generateRouteConfigs([
{ path: '/users/{id}', component: 'UserDetail' },
{ path: '/users/{id}/settings', component: 'UserSettings' },
{ path: '/projects/{projectId}/tasks/{taskId}', component: 'TaskDetail' }
]);
console.log(routeConfigs);
// [
// { path: '/users/:id', component: 'UserDetail', exact: true },
// { path: '/users/:id/settings', component: 'UserSettings', exact: true },
// { path: '/projects/:projectId/tasks/:taskId', component: 'TaskDetail', exact: true }
// ]Next.js dynamic route generation
class NextJsRouteGenerator {
generateFileStructure(openApiPaths: string[]) {
return openApiPaths.map(path => {
// Convert to Next.js file-based routing syntax
const routerPath = toPathParams(path);
const fileName = routerPath
.replace(/:/g, '[') // :id becomes [id
.replace(/\/\[([^\]]+)/g, '/[$1]') // [id becomes [id]
.replace(/^\//,'') // Remove leading slash
+ '.tsx';
return {
originalPath: path,
routerPath,
fileName
};
});
}
}
const generator = new NextJsRouteGenerator();
const structure = generator.generateFileStructure([
'/users/{id}',
'/posts/{slug}/comments/{commentId}'
]);
console.log(structure);
// [
// {
// originalPath: '/users/{id}',
// routerPath: '/users/:id',
// fileName: 'users/[id].tsx'
// },
// {
// originalPath: '/posts/{slug}/comments/{commentId}',
// routerPath: '/posts/:slug/comments/:commentId',
// fileName: 'posts/[slug]/comments/[commentId].tsx'
// }
// ]Integration with path matching
import { matchPath } from 'react-router-dom';
class PathMatcher {
createMatcher(openApiPath: string) {
const routerPath = toPathParams(openApiPath);
return (pathname: string) => {
return matchPath(
{ path: routerPath, exact: true },
pathname
);
};
}
}
const matcher = new PathMatcher();
const userMatcher = matcher.createMatcher('/users/{id}');
const match = userMatcher('/users/123');
console.log(match?.params); // { id: '123' }Returns
string
React Router path string with :parameter syntax