-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
55 lines (53 loc) · 1.4 KB
/
index.ts
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
import { Dict } from "../types";
export function useCookies(cookies: string = document.cookie) {
const cookiesDict = new Cookies(cookies);
function cookie() {
return {
get(key: string) {
return cookiesDict.getOne(key);
},
set(key: string, value: string) {
cookiesDict.setValue(key, value);
},
all() {
return cookiesDict.getAll();
},
toString() {
return cookiesDict.toString();
},
};
}
return cookie();
}
export class Cookies {
cookies: Dict<string, string>;
constructor(cookies: string) {
this.cookies = this.parse(cookies);
}
parse(cookieString: string) {
const cookieDict: Dict<string, string> = {};
cookieString = cookieString.replace(/\s/g, '');
for (let cookie of cookieString.split(';')) {
cookie = cookie.trim();
const [key, val] = cookie.split('=');
cookieDict[key] = val;
}
return cookieDict;
}
toString() {
const cookieString: string[] = [];
Object.keys(this.cookies).forEach(key => {
cookieString.push(`${key}=${this.cookies[key]}`);
});
return cookieString.join(';');
}
setValue(key: string, value: string) {
this.cookies[key] = value;
}
getOne(key: string) {
return this.cookies[key];
}
getAll() {
return this.cookies;
}
}