-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
25 lines (22 loc) · 920 Bytes
/
index.js
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
/**
* Build cookie string using givin options
* @param {string} key Key for cookie
* @param {string} value Value for cookie
* @param {Object} [opts={}] Additional options e.g. path or domain
* @return {string} Representation of cookie that can be stored
*/
module.exports = function (key, value, opts = {}) {
const {path, domain, maxAge, expires, secure} = opts;
// Encoding of key and value
key = key.replace(/[^#$&+\^`|]/g, encodeURIComponent).replace(/\(/g, '%28').replace(/\)/g, '%29');
value = (String(value)).replace(/[^!#$&-+\--:<-\[\]-~]/g, encodeURIComponent);
const cookieStr = [
`${key && value ? key + '=' + value : ''}`,
`${path ? ';path=' + path : ''}`,
`${domain ? ';domain=' + domain : ''}`,
`${maxAge ? ';max-age=' + maxAge : ''}`,
`${expires ? ';expires=' + expires.toUTCString() : ''}`,
`${secure ? ';secure' : ''}`
].join('');
return cookieStr;
};