datasquirel/package-shared/utils/backend/parseCookies.js

57 lines
1.5 KiB
JavaScript
Raw Normal View History

2024-11-06 11:58:41 +00:00
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
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
2024-12-10 14:20:48 +00:00
* @param {http.IncomingMessage & Object<string, any>} [params.request] - HTTPS request object
2024-11-06 11:58:41 +00:00
*
2024-12-10 14:20:48 +00:00
* @returns {Object<string, any>}
2024-11-06 11:58:41 +00:00
*/
module.exports = function ({ request }) {
2024-12-10 14:20:48 +00:00
if (!request) return {};
2024-11-06 11:58:41 +00:00
/** @type {string | undefined} */
const cookieString = request.headers.cookie;
if (!cookieString || typeof cookieString !== "string") {
2024-12-10 14:20:48 +00:00
return {};
2024-11-06 11:58:41 +00:00
}
/** @type {string[]} */
const cookieSplitArray = cookieString.split(";");
/** @type {*} */
let cookieObject = {};
cookieSplitArray.forEach((keyValueString) => {
const [key, value] = keyValueString.split("=");
if (key && typeof key == "string") {
cookieObject[key.replace(/^ +| +$/, "")] =
value && typeof value == "string"
? value.replace(/^ +| +$/, "")
: null;
}
});
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
return cookieObject;
};