forked from amplitude/Amplitude-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetadata-storage.js
72 lines (61 loc) · 1.75 KB
/
metadata-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
/*
* Persist SDK event metadata
* Uses cookie if available, otherwise fallback to localstorage.
*/
import Base64 from './base64';
import baseCookie from './base-cookie';
class MetadataStorage {
constructor({storageKey, secure, expirationDays, path}) {
this.storageKey = storageKey;
this.secure = secure;
this.expirationDays = expirationDays;
this.path = path;
}
getCookieStorageKey() {
return `${this.storageKey}`;
}
save({ deviceId, userId, optOut, sessionId, lastEventTime, eventId, identifyId, sequenceNumber }) {
// do not change the order of these items
const value = [
deviceId,
Base64.encode(userId || ''),
optOut ? '1' : '',
sessionId ? sessionId.toString(32) : '0',
lastEventTime ? lastEventTime.toString(32) : '0',
eventId ? eventId.toString(32) : '0',
identifyId ? identifyId.toString(32) : '0',
sequenceNumber ? sequenceNumber.toString(32) : '0'
].join('.');
baseCookie.set(
this.getCookieStorageKey(),
value,
{ secure: this.secure, expirationDays: this.expirationDays, path: this.path }
);
}
load() {
const str = baseCookie.get(this.getCookieStorageKey() + '=');
if (!str) {
return null;
}
const values = str.split('.');
let userId = null;
if (values[1]) {
try {
userId = Base64.decode(values[1]);
} catch (e) {
userId = null;
}
}
return {
deviceId: values[0],
userId,
optOut: values[2] === '1',
sessionId: parseInt(values[3], 32),
lastEventTime: parseInt(values[4], 32),
eventId: parseInt(values[5], 32),
identifyId: parseInt(values[6], 32),
sequenceNumber: parseInt(values[7], 32)
};
}
}
export default MetadataStorage;