visitor-segments
Version:
Hellobar Segments.
63 lines (62 loc) • 2.21 kB
JavaScript
"use strict";
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _Visitor_handlers;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Visitor = void 0;
const dateUtils_1 = require("./lib/dateUtils");
const valueStorage_1 = require("./valueStorage");
class Visitor {
constructor(key, adapter, expiresInDays = 365 * 5) {
_Visitor_handlers.set(this, []);
this.storage = new valueStorage_1.ValueStorage(new adapter(), expiresInDays * dateUtils_1.MINUTES_IN_DAY);
this.key = key;
this.data = {};
this.load();
}
onUpdate(handler) {
__classPrivateFieldGet(this, _Visitor_handlers, "f").push(handler);
}
getValue(key) {
return this.data[key];
}
setValue(key, value) {
if (typeof this.getValue(key) !== 'object' && this.getValue(key) !== value) {
this.data[key] = value;
this.save();
__classPrivateFieldGet(this, _Visitor_handlers, "f").forEach((handler) => handler.call(handler.prototype, key, value));
}
else {
this.data[key] = value;
this.save();
}
}
setValueOnce(key, value) {
const currentValue = this.getValue(key);
if (currentValue === null || currentValue === undefined) {
this.setValue(key, value);
}
}
removeValue(key) {
delete this.data[key];
this.save();
}
now() {
return (0, dateUtils_1.now)();
}
clear() {
this.data = {};
this.save();
}
save() {
this.storage.setValue(this.key, this.data);
}
load() {
this.data = this.storage.getValue(this.key) || {};
}
}
exports.Visitor = Visitor;
_Visitor_handlers = new WeakMap();