35 lines
915 B
TypeScript
35 lines
915 B
TypeScript
import { APIPathsData, APIPathsParams, APIPathsQuery } from "../../types";
|
|
import deserializeQuery from "../../utils/deserialize-query";
|
|
|
|
export function grabPathData<
|
|
T extends { [k: string]: any } = { [k: string]: any }
|
|
>({ href, basePath }: APIPathsParams<T>): APIPathsData<T> {
|
|
const urlObj = new URL(href);
|
|
|
|
const pathname = basePath
|
|
? urlObj.pathname.replace(basePath, "")
|
|
: urlObj.pathname;
|
|
|
|
const urlArray = pathname.split("/").filter((u) => Boolean(u.match(/./)));
|
|
|
|
const table = urlArray[0];
|
|
const targetId = urlArray[1];
|
|
|
|
let query = (
|
|
urlObj?.searchParams
|
|
? deserializeQuery(Object.fromEntries(urlObj.searchParams))
|
|
: undefined
|
|
) as APIPathsQuery<T> | undefined;
|
|
|
|
if (!table) {
|
|
throw new Error(`No Table Found`);
|
|
}
|
|
|
|
return {
|
|
table,
|
|
targetId,
|
|
query,
|
|
url: urlObj,
|
|
};
|
|
}
|