All files / src/http/utility parse-cookie.ts

13.64% Statements 3/22
0% Branches 0/6
0% Functions 0/3
13.64% Lines 3/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 5618x               18x                                                                                           18x  
import CookieAttribute from 'http/enum/cookie-attribute';
 
type CookieValue = string | boolean;
 
type ParsedCookie = {
	[key in CookieAttribute]?: CookieValue;
};
 
const SUPPORTED_ATTRIBUTES = Object.values(CookieAttribute);
 
function parseCookiePart(
	cookie_part: string
): [CookieAttribute, CookieValue] | null {
	const delimiter_index = cookie_part.indexOf('=');
 
	let cookie_attribute;
	let cookie_value;
 
	if (delimiter_index === -1) {
		cookie_attribute = cookie_part;
		cookie_value = true;
	} else {
		cookie_attribute = cookie_part.slice(0, delimiter_index);
		cookie_value = cookie_part.slice(delimiter_index + 1).trim();
	}
 
	cookie_attribute = cookie_attribute.trim() as CookieAttribute;
 
	if (!SUPPORTED_ATTRIBUTES.includes(cookie_attribute)) {
		return null;
	}
 
	return [cookie_attribute, cookie_value];
}
 
function parseCookie(cookie: string): ParsedCookie {
	const parts = cookie.split(';');
	const result: ParsedCookie = {};
 
	parts.forEach((part) => {
		const tuple = parseCookiePart(part);
 
		if (tuple === null) {
			return;
		}
 
		const [cookie_attribute, cookie_value] = tuple;
 
		result[cookie_attribute] = cookie_value;
	});
 
	return result;
}
 
export default parseCookie;