59 lines
1.7 KiB
JavaScript
59 lines
1.7 KiB
JavaScript
// @ts-check
|
|
|
|
const http = require("http");
|
|
|
|
/**
|
|
* Parse request cookies
|
|
* ===================================================
|
|
*
|
|
* @description This function takes in a request object and
|
|
* returns the cookies as a JS object
|
|
*
|
|
* @async
|
|
*
|
|
* @param {object} params - main params object
|
|
* @param {http.IncomingMessage & Object<string, any>} [params.request] - HTTPS request object
|
|
* @param {string} [params.cookieString]
|
|
*
|
|
* @returns {Object<string, string>}
|
|
*/
|
|
module.exports = function parseCookies({ request, cookieString }) {
|
|
try {
|
|
/** @type {string | undefined} */
|
|
const cookieStr = request
|
|
? request.headers.cookie
|
|
: cookieString
|
|
? cookieString
|
|
: undefined;
|
|
|
|
if (!cookieStr) return {};
|
|
|
|
if (!cookieStr || typeof cookieStr !== "string") {
|
|
return {};
|
|
}
|
|
|
|
/** @type {string[]} */
|
|
const cookieSplitArray = cookieStr.split(";");
|
|
|
|
/** @type {Object<string, string>} */
|
|
let cookieObject = {};
|
|
|
|
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(/^ +| +$/, "")
|
|
: "";
|
|
}
|
|
});
|
|
|
|
return cookieObject;
|
|
} catch (/** @type {any} */ error) {
|
|
console.log(`ERROR parsing cookies: ${error.message}`);
|
|
|
|
return {};
|
|
}
|
|
};
|