PadManager: Refactor padList to avoid duplicate loads

This commit is contained in:
Richard Hansen 2022-01-02 20:40:06 -05:00
parent 66ce2b50a9
commit fd9b770579

View file

@ -50,59 +50,41 @@ const globalPads = {
* *
* Updated without db access as new pads are created/old ones removed. * Updated without db access as new pads are created/old ones removed.
*/ */
const padList = { const padList = new class {
list: new Set(), constructor() {
cachedList: undefined, this._cachedList = null;
initiated: false, this._list = new Set();
async init() { this._loaded = null;
const dbData = await db.findKeys('pad:*', '*:*:*'); }
if (dbData != null) {
this.initiated = true;
for (const val of dbData) {
this.addPad(val.replace(/^pad:/, ''), false);
}
}
return this;
},
async load() {
if (!this.initiated) {
return this.init();
}
return this;
},
/** /**
* Returns all pads in alphabetical order as array. * Returns all pads in alphabetical order as array.
*/ */
async getPads() { async getPads() {
await this.load(); if (!this._loaded) {
this._loaded = (async () => {
if (!this.cachedList) { const dbData = await db.findKeys('pad:*', '*:*:*');
this.cachedList = Array.from(this.list).sort(); if (dbData == null) return;
for (const val of dbData) this.addPad(val.replace(/^pad:/, ''));
})();
} }
await this._loaded;
if (!this._cachedList) this._cachedList = [...this._list].sort();
return this._cachedList;
}
return this.cachedList;
},
addPad(name) { addPad(name) {
if (!this.initiated) return; if (this._list.has(name)) return;
this._list.add(name);
this._cachedList = null;
}
if (!this.list.has(name)) {
this.list.add(name);
this.cachedList = undefined;
}
},
removePad(name) { removePad(name) {
if (!this.initiated) return; if (!this._list.has(name)) return;
this._list.delete(name);
if (this.list.has(name)) { this._cachedList = null;
this.list.delete(name); }
this.cachedList = undefined; }();
}
},
};
// initialises the all-knowing data structure // initialises the all-knowing data structure