datasquirel/utils/functions/parseCookies.js

69 lines
1.9 KiB
JavaScript
Raw Normal View History

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