2024-11-06 11:58:41 +00:00
|
|
|
// @ts-check
|
|
|
|
|
|
|
|
const http = require("http");
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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
|
|
|
*
|
|
|
|
* @async
|
|
|
|
*
|
|
|
|
* @param {object} params - main params object
|
2024-12-10 14:20:48 +00:00
|
|
|
* @param {http.IncomingMessage & Object<string, any>} [params.request] - HTTPS request object
|
2024-12-13 13:01:55 +00:00
|
|
|
* @param {string} [params.cookieString]
|
2024-11-06 11:58:41 +00:00
|
|
|
*
|
2024-12-13 13:01:55 +00:00
|
|
|
* @returns {Object<string, string>}
|
2024-11-06 11:58:41 +00:00
|
|
|
*/
|
2024-12-13 13:01:55 +00:00
|
|
|
module.exports = function ({ request, cookieString }) {
|
|
|
|
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
|
|
|
|
2024-12-13 13:01:55 +00:00
|
|
|
/** @type {string[]} */
|
|
|
|
const cookieSplitArray = cookieStr.split(";");
|
2024-11-06 11:58:41 +00:00
|
|
|
|
2024-12-13 13:01:55 +00:00
|
|
|
/** @type {Object<string, string>} */
|
|
|
|
let cookieObject = {};
|
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;
|
|
|
|
} catch (/** @type {any} */ error) {
|
|
|
|
console.log(`ERROR parsing cookies: ${error.message}`);
|
2024-11-06 11:58:41 +00:00
|
|
|
|
2024-12-13 13:01:55 +00:00
|
|
|
return {};
|
|
|
|
}
|
2024-11-06 11:58:41 +00:00
|
|
|
};
|