datasquirel/package-shared/api-paths/utils/grab-path-data.ts
2025-12-22 07:18:57 +01:00

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,
};
}