forked from pixeleet/react-cookie
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
91 lines (73 loc) · 1.82 KB
/
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
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
var cookie = require('cookie');
var _rawCookie = {};
var _res = undefined;
function load(name, doNotParse) {
var cookies = (typeof document === 'undefined') ? _rawCookie : cookie.parse(document.cookie);
var cookieVal = cookies && cookies[name];
if (!doNotParse) {
try {
cookieVal = JSON.parse(cookieVal);
} catch(e) {
// Not serialized object
}
}
return cookieVal;
}
function save(name, val, opt) {
_rawCookie[name] = val;
// allow you to work with cookies as objects.
if (typeof val === 'object') {
_rawCookie[name] = JSON.stringify(val);
}
// Cookies only work in the browser
if (typeof document !== 'undefined') {
document.cookie = cookie.serialize(name, _rawCookie[name], opt);
}
if (_res && _res.cookie) {
_res.cookie(name, val, opt);
}
}
function remove(name, opt) {
delete _rawCookie[name];
if (typeof opt === 'undefined') {
opt = {};
} else if (typeof opt === 'string') {
// Will be deprecated in future versions
opt = { path: opt };
}
if (typeof document !== 'undefined') {
opt.expires = new Date(1970, 1, 1, 0, 0, 1);
document.cookie = cookie.serialize(name, '', opt);
}
if (_res && _res.clearCookie) {
_res.clearCookie(name, opt);
}
}
function setRawCookie(rawCookie) {
if (rawCookie) {
_rawCookie = cookie.parse(rawCookie);
} else {
_rawCookie = {};
}
}
function plugToRequest(req, res) {
if (req.cookie) {
_rawCookie = req.cookie;
} else if (req.headers && req.headers.cookie) {
setRawCookie(req.headers.cookie);
} else {
_rawCookie = {};
}
_res = res;
}
var reactCookie = {
load: load,
save: save,
remove: remove,
setRawCookie: setRawCookie,
plugToRequest: plugToRequest
};
if (typeof window !== 'undefined') {
window['reactCookie'] = reactCookie;
}
module.exports = reactCookie;