Skip to content

Commit

Permalink
improve parseCookieString
Browse files Browse the repository at this point in the history
  • Loading branch information
stanislav-atr committed Oct 13, 2022
1 parent ea51d04 commit 99fc8fc
Showing 1 changed file with 18 additions and 17 deletions.
35 changes: 18 additions & 17 deletions src/helpers/cookie-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,22 +59,23 @@ export const parseCookieString = (cookieString) => {
const COOKIE_DELIMITER = '=';
const COOKIE_PAIRS_DELIMITER = ';';

return cookieString
.split(COOKIE_PAIRS_DELIMITER)
.reduce((result, string) => {
const delimiterIndex = string.indexOf(COOKIE_DELIMITER);
let cookieKey;
let cookieValue;
if (delimiterIndex === -1) {
cookieKey = string.trim();
} else {
cookieKey = string.slice(0, delimiterIndex).trim();
cookieValue = string.slice(delimiterIndex + 1);
}
// Get raw cookies
const cookieChunks = cookieString.split(COOKIE_PAIRS_DELIMITER);
const cookieData = {};

return Object.defineProperty(result, cookieKey, {
value: cookieValue || null,
enumerable: true,
});
}, {});
cookieChunks.forEach((singleCookie) => {
let cookieKey;
let cookieValue;
const delimiterIndex = singleCookie.indexOf(COOKIE_DELIMITER);
if (delimiterIndex === -1) {
cookieKey = singleCookie.trim();
} else {
cookieKey = singleCookie.slice(0, delimiterIndex).trim();
cookieValue = singleCookie.slice(delimiterIndex + 1);
}
// Save cookie key=value data with null instead of empty ('') values
cookieData[cookieKey] = cookieValue || null;
});

return cookieData;
};

0 comments on commit 99fc8fc

Please sign in to comment.