lib/request/cookies.js

1.
/**
2.
 * This is the cookies class. With this class you can get the cookies that were sent by the client.
3.
 * @class request.cookies
4.
 * @nofunction
5.
 */
6.
module.exports = class cookies {
7.
	constructor(request) {
8.
		this._cookies = this._parse_cookies(request);
9.
	}
10.

			
11.
	_parse_cookies(request) {
12.
		const header = request.headers().get("cookie");
13.
		const cookies = {};
14.
	
15.
		if(header === undefined) return cookies;
16.
	
17.
		header.split("; ").forEach(cookie => {
18.
			const split_index = cookie.indexOf("=");
19.

			
20.
			if(split_index < 0) return;
21.

			
22.
			const key = cookie.substring(0, split_index).trim();
23.
			const value = cookie.substring(split_index + 1, cookie.length).trim();
24.

			
25.
			if(value.startsWith("\"")) value = value.slice(1, value.length - 1);
26.
			if(value.endsWith("\"")) value = value.slice(0, value.length - 2);
27.

			
28.
			if(cookies[key] !== undefined) return;
29.

			
30.
			cookies[key] = value;
31.
		});
32.
	
33.
		return cookies;
34.
	}
35.

			
36.
	/**
37.
	 * With this function you can get a certain cookie that has been sent by the client. You 
38.
	 * specify the cookie you want to get using the key parameter. If the key parameter isn't a 
39.
	 * string it'll throw a TypeError and when the cookie wasn't found it'll return undefined.
40.
	 * @summary Returns the specified cookie.
41.
	 * @return {String} The specified cookie.
42.
	 * @function get
43.
	 */
44.
	get(key) {
45.
		return this._cookies[key];
46.
	}
47.

			
48.
	/**
49.
	 * This function returns if the client has sent the specified cookie. You can specify the 
50.
	 * cookie you want to check using the key parameter. If the key parameter isn't a string it'll
51.
	 * throw a TypeError.
52.
	 * @summary Checks if the cookie exists.
53.
	 * @return {Boolean} If the cookie exists.
54.
	 * @function has
55.
	 */
56.
	has(key) {
57.
		return this._cookies.includes(key);
58.
	}
59.

			
60.
	/**
61.
	 * This function returns an array of the names of all the cookies that were sent by the client.
62.
	 * @summary Returns an array of all the cookies.
63.
	 * @returns {String[]} An array of all the cookies.
64.
	 * @function list
65.
	 */
66.
	list() {
67.
		return Object.keys(this._cookies);
68.
	}
69.
}