refactor: enhance category data management in CategoryList and CategoryService by integrating async-mutex for improved concurrency control and simplifying state handling

This commit is contained in:
sebseb7
2025-07-24 07:04:54 +02:00
parent 2f753a81a4
commit b207377a8e
4 changed files with 158 additions and 339 deletions

View File

@@ -1,3 +1,8 @@
import { Mutex } from 'async-mutex';
const mutex = new Mutex();
class CategoryService {
constructor() {
this.get = this.get.bind(this);
@@ -11,26 +16,37 @@ class CategoryService {
return null;
}
get(categoryId, language = "de") {
const cacheKey = `${categoryId}_${language}`;
if (window.categoryCache && window.categoryCache[cacheKey]) {
return Promise.resolve(window.categoryCache[cacheKey]);
}
return new Promise((resolve) => {
window.socketManager.emit("categoryList", {categoryId: categoryId, language: language}, (response) => {
console.log("CategoryService", cacheKey);
if (response.categoryTree) {
if (!window.categoryCache) {
window.categoryCache = {};
async get(categoryId, language = "de") {
return await mutex.runExclusive(async () => {
console.log("mutex locked");
const cacheKey = `${categoryId}_${language}`;
if (window.categoryCache && window.categoryCache[cacheKey]) {
console.log("mutex unlocked and returning cached value");
return Promise.resolve(window.categoryCache[cacheKey]);
}
return new Promise((resolve) => {
window.socketManager.emit("categoryList", {categoryId: categoryId, language: language}, (response) => {
console.log("CategoryService", cacheKey);
if (response.categoryTree) {
if (!window.categoryCache) {
window.categoryCache = {};
}
window.categoryCache[cacheKey] = response.categoryTree;
console.log("mutex unlocked and returning new value");
resolve(response.categoryTree);
} else {
console.log("mutex unlocked and returning null");
resolve(null);
}
window.categoryCache[cacheKey] = response.categoryTree;
resolve(response.categoryTree);
} else {
resolve(null);
}
});
});
});
}
}