dlovely-websocket
Version:
WebSocket For Dlovely
73 lines (72 loc) • 2.65 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SocketCache = void 0;
const common_1 = require("./common");
class SocketCache {
name;
key;
broadcast;
constructor(name, init, key, control) {
this.name = name;
this.key = key;
this.broadcast = (type, data, key) => control.broadcast(conn => conn.sendSign(`${this.name}-${type}`, { data, key }));
const valsHandle = (vals) => {
vals.forEach(val => {
const key_value = val[key];
if (!['string', 'number'].includes(typeof key_value))
return;
this._store.set(val[key], val);
});
this.broadcast('init', vals, key);
control.tigger.set(name, conn => {
const data = [...this._store.values()];
conn.sendSign(`${this.name}-init`, { data, key });
});
common_1.toast.log(`角色${control.name}已挂载缓冲器${name}`);
};
if (typeof init === 'function') {
const result = init();
if (result instanceof Promise)
result.then(valsHandle);
else
valsHandle(result);
}
else
valsHandle(init);
}
_store = new Map();
get state() {
return [...this._store.keys()];
}
get size() {
return this._store.size;
}
get(key) {
return this._store.get(key);
}
add(val) {
const key = val[this.key];
if (!['string', 'number'].includes(typeof key))
return common_1.toast.error(`新增一项数据时,其索引值不为字符串或数字`, val);
if (this._store.has(key))
return common_1.toast.error(`新增一项数据时,该键已存在`, val);
this._store.set(key, val);
this.broadcast('add', val, key);
}
set(val) {
const key = val[this.key];
if (!['string', 'number'].includes(typeof key))
return common_1.toast.error(`设置一项数据时,其索引值不为字符串或数字`, val);
if (!this._store.has(key))
common_1.toast.error(`设置一项数据时,该键不存在`, val);
this._store.set(key, val);
this.broadcast('set', val, key);
}
del(key) {
if (!this._store.has(key))
return common_1.toast.error(`要删除的键不存在`);
this._store.delete(key);
this.broadcast('del', null, key);
}
}
exports.SocketCache = SocketCache;