2025-01-10 19:10:28 +00:00
|
|
|
import { IncomingMessage } from "http";
|
2024-11-06 11:58:41 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Parse request cookies
|
2024-12-13 13:01:55 +00:00
|
|
|
* ===================================================
|
2024-11-06 11:58:41 +00:00
|
|
|
*
|
2024-12-13 13:01:55 +00:00
|
|
|
* @description This function takes in a request object and
|
|
|
|
* returns the cookies as a JS object
|
2024-11-06 11:58:41 +00:00
|
|
|
*/
|
2025-01-10 19:10:28 +00:00
|
|
|
export default function parseCookies({
|
|
|
|
request,
|
|
|
|
cookieString,
|
|
|
|
}: {
|
|
|
|
request?: IncomingMessage & { [s: string]: any };
|
|
|
|
cookieString?: string;
|
|
|
|
}): { [s: string]: string } {
|
2024-12-13 13:01:55 +00:00
|
|
|
try {
|
|
|
|
/** @type {string | undefined} */
|
|
|
|
const cookieStr = request
|
|
|
|
? request.headers.cookie
|
|
|
|
: cookieString
|
|
|
|
? cookieString
|
|
|
|
: undefined;
|
|
|
|
|
|
|
|
if (!cookieStr) return {};
|
|
|
|
|
|
|
|
if (!cookieStr || typeof cookieStr !== "string") {
|
|
|
|
return {};
|
|
|
|
}
|
2024-11-06 11:58:41 +00:00
|
|
|
|
2025-01-10 19:10:28 +00:00
|
|
|
const cookieSplitArray: string[] = cookieStr.split(";");
|
2024-11-06 11:58:41 +00:00
|
|
|
|
2025-01-10 19:10:28 +00:00
|
|
|
let cookieObject: { [k: string]: string } = {};
|
2024-11-06 11:58:41 +00:00
|
|
|
|
2024-12-13 13:01:55 +00:00
|
|
|
cookieSplitArray.forEach((keyValueString) => {
|
|
|
|
const [key, value] = keyValueString.split("=");
|
|
|
|
if (key && typeof key == "string") {
|
|
|
|
const parsedKey = key.replace(/^ +| +$/, "");
|
|
|
|
cookieObject[parsedKey] =
|
|
|
|
value && typeof value == "string"
|
|
|
|
? value.replace(/^ +| +$/, "")
|
|
|
|
: "";
|
|
|
|
}
|
|
|
|
});
|
2024-11-06 11:58:41 +00:00
|
|
|
|
2024-12-13 13:01:55 +00:00
|
|
|
return cookieObject;
|
2025-01-10 19:10:28 +00:00
|
|
|
} catch (error: any) {
|
2024-12-13 13:01:55 +00:00
|
|
|
console.log(`ERROR parsing cookies: ${error.message}`);
|
2024-11-06 11:58:41 +00:00
|
|
|
|
2024-12-13 13:01:55 +00:00
|
|
|
return {};
|
|
|
|
}
|
2025-01-10 19:10:28 +00:00
|
|
|
}
|