UNPKG

@iamsquare/cookie-parse

Version:
35 lines (34 loc) 1.55 kB
import { map, pipe, split, trim, includes, slice, ifElse, identity, replace, always, filter } from 'ramda'; import { isNotNil, isTrue, isValidNumber, isNotNilOrEmpty } from 'ramda-adjunct'; const HTTP_ONLY_PREFIX = '#HttpOnly_'; const TRUE_CONST = 'TRUE'; export function stringIsTrue(str) { return str.toUpperCase() === TRUE_CONST; } export function applyOnFalse(bool, onFalse) { return ifElse(() => isTrue(bool), identity, onFalse); } export function splitString(separator, options) { return pipe(split(separator), applyOnFalse(options?.skipTrim, map(trim)), applyOnFalse(options?.skipFilter, filter(isNotNilOrEmpty))); } export function nameValuePairToCookie(tuple) { const [name, value] = tuple; return { name, value: ifElse(isNotNil, identity, always(name))(value) }; } export function cookieToNameValuePair(cookie) { return !cookie.value || cookie.name === cookie.value ? cookie.name : `${cookie.name}=${cookie.value}`; } export function arrayToCookie(array) { const [domain, crossDomain, path, https, expires, name, value] = array; const httpOnly = includes(HTTP_ONLY_PREFIX, domain); const parsedExpires = Number.parseInt(expires, 10); return { ...nameValuePairToCookie([name, value]), domain: pipe(applyOnFalse(!httpOnly, slice(HTTP_ONLY_PREFIX.length, Infinity)), replace(/^\./, ''))(domain), crossDomain: stringIsTrue(crossDomain), path, httpOnly, https: stringIsTrue(https), expires: isValidNumber(parsedExpires) ? parsedExpires : 0 }; }