auto(agent): added try/catch blocks and improved error handling in helpRequests.js
This commit is contained in:
parent
fe6c17309a
commit
6539762c92
1 changed files with 30 additions and 20 deletions
|
|
@ -6,31 +6,41 @@ import { requireAuth } from '../middleware/auth.js';
|
|||
const router = Router();
|
||||
|
||||
router.get('/', async (_req, res) => {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT hr.id, hr.title, hr.description, hr.value_chf, hr.status, hr.created_at, u.display_name requester_name
|
||||
FROM help_requests hr
|
||||
JOIN users u ON u.id = hr.requester_id
|
||||
ORDER BY hr.created_at DESC`
|
||||
);
|
||||
res.json(rows);
|
||||
try {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT hr.id, hr.title, hr.description, hr.value_chf, hr.status, hr.created_at, u.display_name requester_name
|
||||
FROM help_requests hr
|
||||
JOIN users u ON u.id = hr.requester_id
|
||||
ORDER BY hr.created_at DESC`
|
||||
);
|
||||
res.json(rows);
|
||||
} catch (error) {
|
||||
console.error('Error fetching help requests:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/', requireAuth, async (req, res) => {
|
||||
const parsed = z.object({
|
||||
title: z.string().min(3).max(180),
|
||||
description: z.string().min(5),
|
||||
valueChf: z.number().positive()
|
||||
}).safeParse(req.body);
|
||||
try {
|
||||
const parsed = z.object({
|
||||
title: z.string().min(3).max(180),
|
||||
description: z.string().min(5),
|
||||
valueChf: z.number().positive()
|
||||
}).safeParse(req.body);
|
||||
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const { title, description, valueChf } = parsed.data;
|
||||
const [result] = await pool.query(
|
||||
'INSERT INTO help_requests (requester_id, title, description, value_chf) VALUES (?, ?, ?, ?)',
|
||||
[req.user.userId, title, description, valueChf]
|
||||
);
|
||||
const { title, description, valueChf } = parsed.data;
|
||||
const [result] = await pool.query(
|
||||
'INSERT INTO help_requests (requester_id, title, description, value_chf) VALUES (?, ?, ?, ?)',
|
||||
[req.user.userId, title, description, valueChf]
|
||||
);
|
||||
|
||||
res.status(201).json({ id: result.insertId });
|
||||
res.status(201).json({ id: result.insertId });
|
||||
} catch (error) {
|
||||
console.error('Error creating help request:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
Loading…
Add table
Add a link
Reference in a new issue