Neue Seite um Betriebe zu überwachen
This commit is contained in:
75
services/userPreferencesStore.js
Normal file
75
services/userPreferencesStore.js
Normal file
@@ -0,0 +1,75 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const PREF_DIR = path.join(__dirname, '..', 'config');
|
||||
|
||||
const DEFAULT_PREFERENCES = {
|
||||
location: null
|
||||
};
|
||||
|
||||
function ensureDir() {
|
||||
if (!fs.existsSync(PREF_DIR)) {
|
||||
fs.mkdirSync(PREF_DIR, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
function getPreferencesPath(profileId = 'shared') {
|
||||
return path.join(PREF_DIR, `${profileId}-preferences.json`);
|
||||
}
|
||||
|
||||
function sanitizeLocation(location) {
|
||||
if (!location) {
|
||||
return null;
|
||||
}
|
||||
const lat = Number(location.lat);
|
||||
const lon = Number(location.lon);
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lon)) {
|
||||
return null;
|
||||
}
|
||||
if (lat < -90 || lat > 90 || lon < -180 || lon > 180) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
lat,
|
||||
lon,
|
||||
updatedAt: Date.now()
|
||||
};
|
||||
}
|
||||
|
||||
function readPreferences(profileId) {
|
||||
ensureDir();
|
||||
const filePath = getPreferencesPath(profileId);
|
||||
if (!fs.existsSync(filePath)) {
|
||||
fs.writeFileSync(filePath, JSON.stringify(DEFAULT_PREFERENCES, null, 2));
|
||||
return { ...DEFAULT_PREFERENCES };
|
||||
}
|
||||
try {
|
||||
const raw = fs.readFileSync(filePath, 'utf8');
|
||||
const parsed = JSON.parse(raw);
|
||||
return {
|
||||
location: sanitizeLocation(parsed.location) || null
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(`[PREFERENCES] Konnte Datei ${filePath} nicht lesen:`, error.message);
|
||||
return { ...DEFAULT_PREFERENCES };
|
||||
}
|
||||
}
|
||||
|
||||
function writePreferences(profileId, patch = {}) {
|
||||
const current = readPreferences(profileId);
|
||||
const next = {
|
||||
location:
|
||||
patch.location === undefined
|
||||
? current.location
|
||||
: sanitizeLocation(patch.location)
|
||||
};
|
||||
ensureDir();
|
||||
const filePath = getPreferencesPath(profileId);
|
||||
fs.writeFileSync(filePath, JSON.stringify(next, null, 2));
|
||||
return next;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
readPreferences,
|
||||
writePreferences
|
||||
};
|
||||
Reference in New Issue
Block a user