datasquirel/client/utils/parseClientCookies.ts
2025-01-10 20:10:28 +01:00

35 lines
1.0 KiB
TypeScript

/**
* Parse request cookies
* ============================================================================== *
* @description This function takes in a request object and returns the cookies as a JS object
*/
export default function (): { [s: string]: any } | null {
/**
* Check inputs
*
* @description Check inputs
*/
const cookieString: string | null = document.cookie;
if (!cookieString || typeof cookieString !== "string") {
return null;
}
const cookieSplitArray: string[] = cookieString.split(";");
let cookieObject: { [s: string]: any } = {};
cookieSplitArray.forEach((keyValueString) => {
const [key, value] = keyValueString.split("=");
if (key && typeof key == "string") {
cookieObject[key.replace(/^ +| +$/, "")] =
value && typeof value == "string"
? value.replace(/^ +| +$/, "")
: null;
}
});
return cookieObject;
}