This code violates DRY by duplicating the route handling logic across different endpoints. A better approach would be to create a reusable route handler factory:
const createGetAllHandler = (Model) => async (req, res) => {
try {
const data = await Model.find();
res.json({ success: true, data });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
};
router.get('/users', createGetAllHandler(User));
router.get('/products', createGetAllHandler(Product));
router.get('/orders', createGetAllHandler(Order));
This approach:
1. Eliminates route handler duplication
2. Makes it easy to add new routes
3. Ensures consistent error handling
4. Makes changes to response format easier to maintain