// Route to add a new table
app.post('/table', async (req, res) => {
const { Table_Number } = req.body;
if (!Table_Number) {
return res.status(400).json({ error: 'Table_Number is required.' });
}
try {
const newTable = new Single_Table({ Table_Number });
await newTable.save();
res.status(201).send('Table added successfully');
} catch (err) {
res.status(500).json({ error: 'Failed to add table', details:
err.message });
}
});
app.get(`/table`, async (req, res) => {
try {
const items = await Single_Table.find();
res.status(200).json(items);
} catch (error) {
res.status(500).json({ error: 'An error occurred while fetching the
tables.' });
}
});
// Route to get item by ID
app.get('/table/:id', async (req, res) => {
try {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).json({ error: 'Invalid ID format.' });
}
const item = await Single_Table.findById(id);
if (!item) {
return res.status(404).json({ error: 'Table not found.' });
}
res.status(200).json(item);
} catch (error) {
res.status(500).json({ error: 'An error occurred while fetching the table.'
});
}
});
// Route to delete item
app.delete('/table/:id', async (req, res) => {
try {
const { id } = req.params;
// Check if the provided ID is valid
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).json({ error: 'Invalid ID format.' });
}
// Attempt to find and delete the table entry
const result = await Single_Table.findByIdAndDelete(id);
if (!result) {
return res.status(404).json({ message: 'Table not found' });
}
return res.status(200).json({ message: 'Table deleted successfully' });
} catch (error) {
res.status(500).send({ message: error.message });
}
});
app.put('/servers/:id', async (req, res) => {
try {
const { Name, Last_Name, Adresse, Cin, Salary, Shift, Ratings,
Tables_Under_Control } = req.body; // Extract data from request body
const { id } = req.params; // Extract id from request params
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).json({ error: 'Invalid ID.' });
}
const server = await Servers.findById(id); // Use 'server' variable for
the found document
if (!server) {
return res.status(404).json({ message: 'Server not found' });
}
// Update the server fields
server.Name = Name;
server.Last_Name = Last_Name;
server.Adresse = Adresse;
server.Cin = Cin;
server.Salary = Salary;
server.Shift = Shift;
server.Ratings = Ratings;
server.Tables_Under_Control = Tables_Under_Control; // Ensure it's handled
as an array
const result = await server.save(); // Save the updated server
return res.status(200).json({ message: 'Server updated successfully', data:
result });
} catch (error) {
res.status(500).send({ message: error.message });
}
});