-
Notifications
You must be signed in to change notification settings - Fork 1
/
next-storage.js
88 lines (71 loc) · 2 KB
/
next-storage.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
import { setCookie, parseCookies, destroyCookie } from 'nookies';
/**
* @class NextStorage
*/
export default class NextStorage {
/**
* Constructs a new NextStorage object
* @param {object} ctx Next.js ctx object
* @param {string} domain Cookies domain (required).
* @param {string} [path] Cookies path (default: '/')
* @param {number} [expires] Cookie expiration (in days, default: 365)
* @param {boolean} [secure] Cookie secure flag (default: true)
*/
constructor(ctx, { domain, path = '/', expires = 365, secure = true }) {
if (!domain) {
throw new Error('The domain of cookieStorage can not be undefined.');
}
this.ctx = ctx;
this.domain = domain;
this.path = path;
this.expires = expires;
this.secure = secure;
}
/**
* This is used to set a specific item in storage
* @param {string} key - the key for the item
* @param {string} value - the value
* @returns {string} value that was set
*/
setItem(key, value) {
setCookie(this.ctx, key, value, {
path: this.path,
maxAge: this.expires * 86400,
domain: this.domain,
secure: this.secure,
});
return this.getItem(key);
}
/**
* This is used to get a specific key from storage
* @param {string} key - the key for the item
* This is used to clear the storage
* @returns {string} the data item
*/
getItem(key) {
return parseCookies(this.ctx)[key];
}
/**
* This is used to remove an item from storage
* @param {string} key - the key being set
* @returns {string} value - value that was deleted
*/
removeItem(key) {
const value = this.getItem(key);
destroyCookie(this.ctx, key, {
domain: this.domain,
path: this.path,
secure: this.secure,
});
return value;
}
/**
* This is used to clear the storage
* @returns {object} nothing
*/
clear() {
const cookies = Object.keys(parseCookies(this.ctx));
cookies.forEach(cookie => destroyCookie(this.ctx, cookie));
return {};
}
}