refactoring
This commit is contained in:
84
services/storeWatchStore.js
Normal file
84
services/storeWatchStore.js
Normal file
@@ -0,0 +1,84 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const STORE_WATCH_DIR = path.join(__dirname, '..', 'config');
|
||||
|
||||
function ensureDir() {
|
||||
if (!fs.existsSync(STORE_WATCH_DIR)) {
|
||||
fs.mkdirSync(STORE_WATCH_DIR, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
function getStoreWatchPath(profileId = 'shared') {
|
||||
return path.join(STORE_WATCH_DIR, `${profileId}-store-watch.json`);
|
||||
}
|
||||
|
||||
function sanitizeEntry(entry) {
|
||||
if (!entry || !entry.storeId) {
|
||||
return null;
|
||||
}
|
||||
const normalized = {
|
||||
storeId: String(entry.storeId),
|
||||
storeName: entry.storeName ? String(entry.storeName).trim() : `Store ${entry.storeId}`,
|
||||
regionId: entry.regionId ? String(entry.regionId) : '',
|
||||
regionName: entry.regionName ? String(entry.regionName).trim() : '',
|
||||
lastTeamSearchStatus:
|
||||
entry.lastTeamSearchStatus === 1
|
||||
? 1
|
||||
: entry.lastTeamSearchStatus === 0
|
||||
? 0
|
||||
: null
|
||||
};
|
||||
if (!normalized.regionId) {
|
||||
return null;
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function readStoreWatch(profileId) {
|
||||
ensureDir();
|
||||
const filePath = getStoreWatchPath(profileId);
|
||||
if (!fs.existsSync(filePath)) {
|
||||
fs.writeFileSync(filePath, JSON.stringify([], null, 2));
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
const raw = fs.readFileSync(filePath, 'utf8');
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!Array.isArray(parsed)) {
|
||||
return [];
|
||||
}
|
||||
const unique = new Map();
|
||||
parsed.forEach((entry) => {
|
||||
const sanitized = sanitizeEntry(entry);
|
||||
if (sanitized) {
|
||||
unique.set(sanitized.storeId, sanitized);
|
||||
}
|
||||
});
|
||||
return Array.from(unique.values());
|
||||
} catch (error) {
|
||||
console.error(`[STORE-WATCH] Konnte Datei ${filePath} nicht lesen:`, error.message);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeStoreWatch(profileId, entries = []) {
|
||||
const sanitized = [];
|
||||
const seen = new Set();
|
||||
entries.forEach((entry) => {
|
||||
const normalized = sanitizeEntry(entry);
|
||||
if (normalized && !seen.has(normalized.storeId)) {
|
||||
sanitized.push(normalized);
|
||||
seen.add(normalized.storeId);
|
||||
}
|
||||
});
|
||||
ensureDir();
|
||||
const filePath = getStoreWatchPath(profileId);
|
||||
fs.writeFileSync(filePath, JSON.stringify(sanitized, null, 2));
|
||||
return sanitized;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
readStoreWatch,
|
||||
writeStoreWatch
|
||||
};
|
||||
Reference in New Issue
Block a user