feat: add data manager module and enhance API logging for debugging
This commit is contained in:
parent
3ea2f36c5c
commit
20b5e4b06f
44
data-api.js
44
data-api.js
@ -63,15 +63,21 @@ if (!fs.existsSync(DATA_FILE)) {
|
||||
// GET endpoint to retrieve data
|
||||
app.get('/data/weight-tracker-data.json', (req, res) => {
|
||||
try {
|
||||
console.log(`[DEBUG] GET request received for ${DATA_FILE}`);
|
||||
console.log(`[DEBUG] File exists: ${fs.existsSync(DATA_FILE)}`);
|
||||
|
||||
if (fs.existsSync(DATA_FILE)) {
|
||||
const data = fs.readFileSync(DATA_FILE, 'utf8');
|
||||
console.log(`[DEBUG] Data read from file: ${data.substring(0, 100)}...`);
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.send(data);
|
||||
console.log(`[DEBUG] Data sent to client`);
|
||||
} else {
|
||||
console.log(`[DEBUG] Data file not found at ${DATA_FILE}`);
|
||||
res.status(404).send({ error: 'Data file not found' });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error reading data file:', error);
|
||||
console.error('[DEBUG] Error reading data file:', error);
|
||||
res.status(500).send({ error: 'Failed to read data file' });
|
||||
}
|
||||
});
|
||||
@ -79,20 +85,46 @@ app.get('/data/weight-tracker-data.json', (req, res) => {
|
||||
// PUT endpoint to update data
|
||||
app.put('/data/weight-tracker-data.json', (req, res) => {
|
||||
try {
|
||||
console.log(`[DEBUG] PUT request received for ${DATA_FILE}`);
|
||||
const data = req.body;
|
||||
|
||||
// Log request body summary
|
||||
console.log(`[DEBUG] Request body received:`, {
|
||||
hasData: !!data,
|
||||
hasWeights: data && !!data.weights,
|
||||
weightCount: data && data.weights ? data.weights.length : 0,
|
||||
hasMeals: data && !!data.meals,
|
||||
mealCount: data && data.meals ? data.meals.length : 0
|
||||
});
|
||||
|
||||
// Validate data structure
|
||||
if (!data || !data.weights || !data.meals) {
|
||||
console.log(`[DEBUG] Invalid data structure received`);
|
||||
return res.status(400).send({ error: 'Invalid data structure' });
|
||||
}
|
||||
|
||||
// Write to file
|
||||
fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2));
|
||||
res.send({ success: true, message: 'Data saved successfully' });
|
||||
// Ensure data directory exists
|
||||
if (!fs.existsSync(DATA_DIR)) {
|
||||
console.log(`[DEBUG] Creating data directory: ${DATA_DIR}`);
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
console.log(`Data updated: ${new Date().toISOString()}`);
|
||||
// Write to file
|
||||
console.log(`[DEBUG] Writing data to file: ${DATA_FILE}`);
|
||||
fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2));
|
||||
|
||||
// Verify file was written
|
||||
const fileExists = fs.existsSync(DATA_FILE);
|
||||
console.log(`[DEBUG] File exists after write: ${fileExists}`);
|
||||
if (fileExists) {
|
||||
const stats = fs.statSync(DATA_FILE);
|
||||
console.log(`[DEBUG] File size after write: ${stats.size} bytes`);
|
||||
}
|
||||
|
||||
res.send({ success: true, message: 'Data saved successfully' });
|
||||
console.log(`[DEBUG] Data updated: ${new Date().toISOString()}`);
|
||||
} catch (error) {
|
||||
console.error('Error writing data file:', error);
|
||||
console.error('[DEBUG] Error writing data file:', error);
|
||||
res.status(500).send({ error: 'Failed to write data file' });
|
||||
}
|
||||
});
|
||||
|
||||
@ -20,7 +20,7 @@ const DataManager = (() => {
|
||||
return true;
|
||||
};
|
||||
|
||||
// Storage file path for Docker environment
|
||||
// Storage file path for Docker environment - this needs to match the API endpoint in data-api.js
|
||||
const serverDataPath = '/data/weight-tracker-data.json';
|
||||
|
||||
/**
|
||||
@ -28,29 +28,47 @@ const DataManager = (() => {
|
||||
*/
|
||||
const init = async () => {
|
||||
try {
|
||||
console.log('Initializing data manager...');
|
||||
console.log('Docker environment detected:', isDockerEnvironment());
|
||||
|
||||
if (isDockerEnvironment()) {
|
||||
// Try to load from server-side storage
|
||||
try {
|
||||
console.log('Attempting to load data from server at:', serverDataPath);
|
||||
const response = await fetch(serverDataPath);
|
||||
console.log('Server response status:', response.status, response.statusText);
|
||||
|
||||
if (response.ok) {
|
||||
appData = await response.json();
|
||||
console.log('Data loaded from server storage');
|
||||
const data = await response.json();
|
||||
console.log('Data received from server:', {
|
||||
hasData: !!data,
|
||||
hasWeights: data && !!data.weights,
|
||||
weightCount: data && data.weights ? data.weights.length : 0,
|
||||
hasMeals: data && !!data.meals,
|
||||
mealCount: data && data.meals ? data.meals.length : 0
|
||||
});
|
||||
appData = data;
|
||||
console.log('Data loaded from server storage successfully');
|
||||
} else {
|
||||
console.log('No server data found. Starting with empty data.');
|
||||
console.log('No server data found or error response. Starting with empty data.');
|
||||
appData = {...defaultData};
|
||||
console.log('Saving default data to server...');
|
||||
await saveData(); // Save default data to server
|
||||
}
|
||||
} catch (serverError) {
|
||||
console.warn('Error loading from server, falling back to localStorage:', serverError);
|
||||
console.warn('Exception loading from server:', serverError);
|
||||
console.log('Falling back to localStorage');
|
||||
loadFromLocalStorage();
|
||||
}
|
||||
} else {
|
||||
// Use localStorage in development environment
|
||||
console.log('Using localStorage in development environment');
|
||||
loadFromLocalStorage();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error initializing data:', error);
|
||||
appData = {...defaultData};
|
||||
console.log('Saving default data due to initialization error');
|
||||
saveData(); // Save default data structure on error
|
||||
}
|
||||
};
|
||||
@ -100,6 +118,13 @@ const DataManager = (() => {
|
||||
*/
|
||||
const saveDataToServer = async () => {
|
||||
try {
|
||||
console.log('Attempting to save data to server at:', serverDataPath);
|
||||
console.log('Data to save:', {
|
||||
weights: appData.weights.length,
|
||||
meals: appData.meals.length,
|
||||
version: appData.version
|
||||
});
|
||||
|
||||
const response = await fetch(serverDataPath, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
@ -109,14 +134,24 @@ const DataManager = (() => {
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
console.log('Data saved to server storage');
|
||||
const result = await response.json();
|
||||
console.log('Server response:', result);
|
||||
console.log('Data saved to server storage successfully');
|
||||
return true;
|
||||
} else {
|
||||
console.error('Error saving data to server:', response.statusText);
|
||||
console.error('Error saving data to server. Status:', response.status, response.statusText);
|
||||
try {
|
||||
const errorData = await response.text();
|
||||
console.error('Error details:', errorData);
|
||||
} catch (e) {
|
||||
console.error('Could not parse error response');
|
||||
}
|
||||
console.log('Falling back to localStorage');
|
||||
return saveDataToLocalStorage(); // Fallback to localStorage
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error saving data to server:', error);
|
||||
console.error('Exception while saving data to server:', error);
|
||||
console.log('Falling back to localStorage');
|
||||
return saveDataToLocalStorage(); // Fallback to localStorage
|
||||
}
|
||||
};
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user