fix: add error handling, empty name guard, and input validation to data module
This commit is contained in:
26
js/data.js
26
js/data.js
@@ -1,9 +1,22 @@
|
||||
export function loadFromJSON(json) {
|
||||
const parsed = JSON.parse(json);
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(json);
|
||||
} catch (e) {
|
||||
throw new Error('Ungültige JSON-Datei: ' + e.message);
|
||||
}
|
||||
if (typeof parsed !== 'object' || parsed === null) {
|
||||
throw new Error('Ungültiges Dateiformat: Objekt erwartet');
|
||||
}
|
||||
return {
|
||||
employees: parsed.employees ?? [],
|
||||
calendar: parsed.calendar ?? { holidays: [], companyClosures: [] },
|
||||
history: parsed.history ?? []
|
||||
employees: Array.isArray(parsed.employees) ? parsed.employees : [],
|
||||
calendar: (parsed.calendar && typeof parsed.calendar === 'object')
|
||||
? {
|
||||
holidays: Array.isArray(parsed.calendar.holidays) ? parsed.calendar.holidays : [],
|
||||
companyClosures: Array.isArray(parsed.calendar.companyClosures) ? parsed.calendar.companyClosures : []
|
||||
}
|
||||
: { holidays: [], companyClosures: [] },
|
||||
history: Array.isArray(parsed.history) ? parsed.history : []
|
||||
};
|
||||
}
|
||||
|
||||
@@ -16,9 +29,11 @@ export function saveToJSON(state) {
|
||||
}
|
||||
|
||||
export function createEmployee(name) {
|
||||
const trimmed = (name ?? '').trim();
|
||||
if (!trimmed) throw new Error('Mitarbeitername darf nicht leer sein');
|
||||
return {
|
||||
id: crypto.randomUUID(),
|
||||
name: name.trim(),
|
||||
name: trimmed,
|
||||
constraints: {
|
||||
neverDays: [],
|
||||
lowPriorityDays: [],
|
||||
@@ -48,6 +63,7 @@ export function toggleClosure(state, isoDate) {
|
||||
|
||||
// Adds entries to history, replacing any existing entries for the same dates
|
||||
export function addHistoryEntries(state, entries) {
|
||||
if (!entries?.length) return;
|
||||
const dates = new Set(entries.map(e => e.date));
|
||||
state.history = state.history.filter(h => !dates.has(h.date));
|
||||
state.history.push(...entries);
|
||||
|
||||
Reference in New Issue
Block a user