mirror of
https://github.com/Alvin-Zilverstand/challenge-11.git
synced 2026-03-06 11:06:21 +01:00
74 lines
2.0 KiB
JavaScript
74 lines
2.0 KiB
JavaScript
const express = require('express');
|
|
const router = express.Router();
|
|
const Customer = require('../models/Customer');
|
|
|
|
// Get all customers
|
|
router.get('/', async (req, res) => {
|
|
try {
|
|
const customers = await Customer.find().sort({ name: 1 });
|
|
res.json(customers);
|
|
} catch (error) {
|
|
console.error('Error fetching customers:', error);
|
|
res.status(500).json({ message: 'Server error' });
|
|
}
|
|
});
|
|
|
|
// Get single customer
|
|
router.get('/:id', async (req, res) => {
|
|
try {
|
|
const customer = await Customer.findById(req.params.id);
|
|
if (!customer) {
|
|
return res.status(404).json({ message: 'Customer not found' });
|
|
}
|
|
res.json(customer);
|
|
} catch (error) {
|
|
console.error('Error fetching customer:', error);
|
|
res.status(500).json({ message: 'Server error' });
|
|
}
|
|
});
|
|
|
|
// Create customer
|
|
router.post('/', async (req, res) => {
|
|
try {
|
|
const customer = new Customer(req.body);
|
|
await customer.save();
|
|
res.status(201).json(customer);
|
|
} catch (error) {
|
|
console.error('Error creating customer:', error);
|
|
res.status(500).json({ message: 'Server error' });
|
|
}
|
|
});
|
|
|
|
// Update customer
|
|
router.put('/:id', async (req, res) => {
|
|
try {
|
|
const customer = await Customer.findByIdAndUpdate(
|
|
req.params.id,
|
|
{ ...req.body, updatedAt: Date.now() },
|
|
{ new: true }
|
|
);
|
|
if (!customer) {
|
|
return res.status(404).json({ message: 'Customer not found' });
|
|
}
|
|
res.json(customer);
|
|
} catch (error) {
|
|
console.error('Error updating customer:', error);
|
|
res.status(500).json({ message: 'Server error' });
|
|
}
|
|
});
|
|
|
|
// Delete customer
|
|
router.delete('/:id', async (req, res) => {
|
|
try {
|
|
const customer = await Customer.findByIdAndDelete(req.params.id);
|
|
if (!customer) {
|
|
return res.status(404).json({ message: 'Customer not found' });
|
|
}
|
|
res.json({ message: 'Customer deleted successfully' });
|
|
} catch (error) {
|
|
console.error('Error deleting customer:', error);
|
|
res.status(500).json({ message: 'Server error' });
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|