datasquirel/utils/functions/parseCookies.js

66 lines
1.7 KiB
JavaScript
Raw Normal View History

2023-06-24 12:09:26 +00:00
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
/**
* 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 {object} params.request - HTTPS request object
*
2023-08-07 03:42:49 +00:00
* @returns {object|null}
2023-06-24 12:09:26 +00:00
*/
module.exports = function ({ request }) {
/**
* Check inputs
*
* @description Check inputs
*/
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/** @type {string|null} */
const cookieString = request.headers.cookie;
if (!cookieString || typeof cookieString !== "string") {
return null;
}
/** @type {string[]} */
const cookieSplitArray = cookieString.split(";");
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;
};
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////