// controllers/itemController.js
class ItemController {
// GET /api/items
async getAll(req, res, next) {
try {
const { page = 1, limit = 10, sort = '-createdAt' } = req.query;
const items = await Item.find()
.sort(sort)
.skip((page - 1) * limit)
.limit(parseInt(limit));
const total = await Item.countDocuments();
res.json({
success: true,
count: items.length,
data: items,
pagination: { page: parseInt(page), limit: parseInt(limit), total }
});
} catch (error) {
next(error);
}
}
// GET /api/items/:id
async getById(req, res, next) {
try {
const item = await Item.findById(req.params.id);
if (!item) {
return res.status(404).json({
success: false,
error: 'Item not found'
});
}
res.json({ success: true, data: item });
} catch (error) {
next(error);
}
}
// POST /api/items
async create(req, res, next) {
try {
const item = await Item.create(req.body);
res.status(201).json({ success: true, data: item });
} catch (error) {
next(error);
}
}
// PUT /api/items/:id
async update(req, res, next) {
try {
const item = await Item.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true, runValidators: true }
);
if (!item) {
return res.status(404).json({
success: false,
error: 'Item not found'
});
}
res.json({ success: true, data: item });
} catch (error) {
next(error);
}
}
// DELETE /api/items/:id
async delete(req, res, next) {
try {
const item = await Item.findByIdAndDelete(req.params.id);
if (!item) {
return res.status(404).json({
success: false,
error: 'Item not found'
});
}
res.status(204).send();
} catch (error) {
next(error);
}
}
}
module.exports = new ItemController();