feat: implement DataManager module and enhance API error handling for empty files
This commit is contained in:
parent
b194bc1226
commit
1dcb6d6631
@ -25,10 +25,16 @@ const DataManager = (() => {
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data && typeof data === 'object') {
|
||||
appData = data;
|
||||
console.log('Successfully loaded data from API.');
|
||||
// Optionally, update localStorage for offline or quick display, but API is truth
|
||||
// saveDataToLocalStorage();
|
||||
// Merge loaded data with defaults to ensure all keys are present
|
||||
appData = {
|
||||
...defaultData, // Start with defaults
|
||||
...data, // Override with loaded data
|
||||
// Ensure critical arrays exist if not in loaded data or if they are not arrays
|
||||
weights: Array.isArray(data.weights) ? data.weights : defaultData.weights,
|
||||
meals: Array.isArray(data.meals) ? data.meals : defaultData.meals,
|
||||
version: data.version || defaultData.version // Ensure version is present
|
||||
};
|
||||
console.log('Successfully loaded and merged data from API.');
|
||||
} else {
|
||||
console.warn('Data from API was not valid JSON or empty. Using default data.');
|
||||
appData = { ...defaultData };
|
||||
|
||||
@ -32,12 +32,17 @@ app.get('/', (req, res) => {
|
||||
console.error('Error reading data file:', err);
|
||||
return res.status(500).send('Error reading data file');
|
||||
}
|
||||
// If file is empty or just whitespace, treat as empty object
|
||||
if (!data || data.trim() === '') {
|
||||
console.log(`Data file at ${DATA_FILE_PATH} is empty, returning empty object.`);
|
||||
return res.json({});
|
||||
}
|
||||
|
||||
try {
|
||||
res.json(JSON.parse(data));
|
||||
} catch (parseErr) {
|
||||
console.error('Error parsing data file content:', parseErr);
|
||||
// If file content is not valid JSON, perhaps return empty or handle error
|
||||
res.status(500).send('Error parsing data file content');
|
||||
console.error(`Error parsing data file content from ${DATA_FILE_PATH}:`, parseErr);
|
||||
return res.status(500).json({ message: 'Error parsing data file content. File may be corrupted.', error: parseErr.message });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user