@sls-next/core
Version:
Handles Next.js routing independent of provider
27 lines (26 loc) • 774 B
JavaScript
import { pathToRegexp } from "path-to-regexp";
/**
* Convert any dynamic route to express route of the dynamic part.
* @param dynamicRoute
*/
const expressifyDynamicRoute = (dynamicRoute) => {
return dynamicRoute
.replace(/\[\[\.\.\.(.*)]]$/, ":$1*")
.replace(/\[\.\.\.(.*)]$/, ":$1*")
.replace(/\[(.*?)]/g, ":$1");
};
/*
* Convert next.js path to regex
* Does not handle optional parts!
*/
export const pathToRegexStr = (path) => {
try {
return pathToRegexp(expressifyDynamicRoute(path))
.toString()
.replace(/\/(.*)\/\i/, "$1");
}
catch (exception) {
console.error(`Unable to convert path to regex: ${path}. Please check for any special characters.`);
throw exception;
}
};