forked from victorsferreira/vue-session
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
107 lines (92 loc) · 2.96 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
var STORAGE = null;
var VueSession = {
key: 'vue-session-key',
flash_key: 'vue-session-flash-key',
setAll: function(all){
STORAGE.setItem(VueSession.key,JSON.stringify(all));
}
}
VueSession.install = function(Vue, options) {
if(options && 'persist' in options && options.persist) STORAGE = window.localStorage;
else STORAGE = window.sessionStorage;
Vue.prototype.$session = {
flash: {
parent: function(){
return Vue.prototype.$session;
},
get: function(key){
var all = this.parent().getAll();
var all_flash = all[VueSession.flash_key] || {};
var flash_value = all_flash[key];
this.remove(key);
return flash_value;
},
set: function(key, value){
var all = this.parent().getAll();
var all_flash = all[VueSession.flash_key] || {};
all_flash[key] = value;
all[VueSession.flash_key] = all_flash;
VueSession.setAll(all);
},
remove: function(key){
var all = this.parent().getAll();
var all_flash = all[VueSession.flash_key] || {};
delete all_flash[key];
all[VueSession.flash_key] = all_flash;
VueSession.setAll(all);
}
},
getAll: function(){
var all = JSON.parse(STORAGE.getItem(VueSession.key));
return all || {};
},
set: function(key,value){
if(key == 'session-id') return false;
var all = this.getAll();
if(!('session-id' in all)){
this.start();
all = this.getAll();
}
all[key] = value;
VueSession.setAll(all);
},
get: function(key){
var all = this.getAll();
return all[key];
},
start: function(){
var all = this.getAll();
all['session-id'] = 'sess:'+Date.now();
VueSession.setAll(all);
},
renew: function(sessionId){
var all = this.getAll();
all['session-id'] = 'sess:' + sessionId;
VueSession.setAll(all);
},
exists: function(){
var all = this.getAll();
return 'session-id' in all;
},
has: function(key){
var all = this.getAll();
return key in all;
},
remove: function(key){
var all = this.getAll();
delete all[key];
VueSession.setAll(all);
},
clear: function(){
var all = this.getAll();
VueSession.setAll({'session-id': all['session-id']});
},
destroy: function(){
VueSession.setAll({});
},
id: function(){
return this.get('session-id');
}
}
};
module.exports = VueSession;