dsql-admin/dsql-app/package-shared/utils/backend/parseCookies.js

59 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

2024-11-06 12:06:51 +00:00
// @ts-check
const http = require("http");
/**
* Parse request cookies
2024-12-15 11:27:16 +00:00
* ===================================================
2024-11-06 12:06:51 +00:00
*
2024-12-15 11:27:16 +00:00
* @description This function takes in a request object and
* returns the cookies as a JS object
2024-11-06 12:06:51 +00:00
*
* @async
*
* @param {object} params - main params object
2024-12-15 11:27:16 +00:00
* @param {http.IncomingMessage & Object<string, any>} [params.request] - HTTPS request object
* @param {string} [params.cookieString]
2024-11-06 12:06:51 +00:00
*
2024-12-15 11:27:16 +00:00
* @returns {Object<string, string>}
2024-11-06 12:06:51 +00:00
*/
2024-12-15 11:27:16 +00:00
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 {};
}
2024-11-06 12:06:51 +00:00
2024-12-15 11:27:16 +00:00
/** @type {string[]} */
const cookieSplitArray = cookieStr.split(";");
2024-11-06 12:06:51 +00:00
2024-12-15 11:27:16 +00:00
/** @type {Object<string, string>} */
let cookieObject = {};
2024-11-06 12:06:51 +00:00
2024-12-15 11:27:16 +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 12:06:51 +00:00
2024-12-15 11:27:16 +00:00
return cookieObject;
} catch (/** @type {any} */ error) {
console.log(`ERROR parsing cookies: ${error.message}`);
2024-11-06 12:06:51 +00:00
2024-12-15 11:27:16 +00:00
return {};
}
2024-11-06 12:06:51 +00:00
};