@iamsquare/cookie-parse
Version:
Cookie string/file parse utilities.
42 lines (41 loc) • 1.85 kB
JavaScript
import { pipe, map, reduce, toLower, replace, head, ifElse, allPass, equals, identity, always, join } from 'ramda';
import { contained, isNotNil, stubNull } from 'ramda-adjunct';
import { nameValuePairToCookie, splitString } from './utils';
export function parseCookieString(string) {
return pipe(splitString(';'), map(pipe(splitString(/=(.+)/, { skipFilter: true }), nameValuePairToCookie)))(string);
}
export function parseSetCookieString(string) {
return pipe(splitString(';'), map(splitString(/=(.+)/, { skipFilter: true })), ([[name, value], ...rest]) => reduce((acc, [k, v]) => {
switch (toLower(k)) {
case 'max-age': {
return { ...acc, maxAge: Number.parseInt(v, 10) };
}
case 'expires': {
return { ...acc, expires: Math.floor(new Date(v).getTime() / 1000) };
}
case 'domain': {
return { ...acc, domain: replace(/^\./, '', v) };
}
case 'path': {
return {
...acc,
path: ifElse(allPass([isNotNil, pipe(head, equals('/'))]), identity, stubNull)(v)
};
}
case 'secure': {
return { ...acc, secure: true };
}
case 'httponly': {
return { ...acc, httpOnly: true };
}
case 'samesite': {
return {
...acc,
sameSite: pipe(toLower, ifElse(contained(['lax', 'strict']), identity, always('none')))(v)
};
}
default:
return { ...acc, extension: [...(acc.extension || []), join('=', [k, v])] };
}
}, { ...nameValuePairToCookie([name, value]), secure: false, httpOnly: false, sameSite: 'none' }, rest))(string);
}