init
This commit is contained in:
commit
04267b3886
100 changed files with 16495 additions and 0 deletions
66
backend/src/routes/items.ts
Normal file
66
backend/src/routes/items.ts
Normal file
|
@ -0,0 +1,66 @@
|
|||
import { Router } from 'express';
|
||||
import Item from '../models/Item.js';
|
||||
import Tag from '../models/Tag.js';
|
||||
import auth from '../middleware/auth.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
/* ──────────── GET: lista completa ──────────── */
|
||||
router.get('/', async (_req, res) => {
|
||||
const items = await Item.find().populate('tags');
|
||||
res.json(items);
|
||||
});
|
||||
|
||||
/* ──────────── GET: ricerca ──────────── */
|
||||
router.get('/search', async (req, res) => {
|
||||
const { query = '', tagIds = '' } = req.query as {
|
||||
query?: string;
|
||||
tagIds?: string;
|
||||
};
|
||||
|
||||
const regex = new RegExp(query, 'i');
|
||||
const filter: any = {
|
||||
$and: [
|
||||
{ $or: [{ name: regex }, { description: regex }] },
|
||||
tagIds ? { tags: { $in: tagIds.split(',') } } : {},
|
||||
],
|
||||
};
|
||||
|
||||
const items = await Item.find(filter).populate('tags');
|
||||
res.json(items);
|
||||
});
|
||||
|
||||
/* ──────────── POST: crea item (protetto) ──────────── */
|
||||
router.post('/', auth, async (req, res) => {
|
||||
const { name, description, tagIds } = req.body as {
|
||||
name: string;
|
||||
description: string;
|
||||
tagIds: string[];
|
||||
};
|
||||
|
||||
const tags = await Tag.find({ _id: { $in: tagIds } });
|
||||
const item = await Item.create({
|
||||
name,
|
||||
description,
|
||||
tags,
|
||||
addedBy: req.user!.email,
|
||||
});
|
||||
|
||||
res.status(201).json(await item.populate('tags'));
|
||||
});
|
||||
|
||||
/* ──────────── DELETE: elimina item (protetto) ──────────── */
|
||||
router.delete('/:id', auth, async (req, res) => {
|
||||
const { id } = req.params;
|
||||
|
||||
const deleted = await Item.findByIdAndDelete(id);
|
||||
if (!deleted) {
|
||||
res.status(404).json({ message: 'Item non trovato' });
|
||||
return;
|
||||
}
|
||||
|
||||
// 204 No Content: operazione riuscita, nessun body
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
export default router;
|
Loading…
Add table
Add a link
Reference in a new issue