Refactor la route de prévisualisation d'image pour améliorer la gestion des erreurs et intégrer le redimensionnement d'image dans des fonctions séparées
This commit is contained in:
@@ -62,45 +62,55 @@ router.get('/images/:measurementId', (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/preview/:projectId/:orderId', async (req, res) => {
|
||||
const projectId = req.params.projectId;
|
||||
const orderId = req.params.orderId;
|
||||
const getImagePath = async (projectId, orderId) => {
|
||||
const query = 'SELECT path FROM public.measurements WHERE project_id = $1 AND order_id = $2';
|
||||
|
||||
try {
|
||||
const result = await db.query(query, [projectId, orderId]);
|
||||
if (result.rows.length === 0) {
|
||||
return res.status(404).json({ error: 'Image not found' });
|
||||
throw new Error('Image not found');
|
||||
}
|
||||
return result.rows[0].path;
|
||||
};
|
||||
|
||||
const imagePath = result.rows[0].path;
|
||||
|
||||
// Vérifier si l'image existe
|
||||
fs.access(imagePath, fs.constants.F_OK, async (err) => {
|
||||
const checkImageExists = (imagePath) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
fs.access(imagePath, fs.constants.F_OK, (err) => {
|
||||
if (err) {
|
||||
console.error('Image not found:', err);
|
||||
return res.status(404).json({ error: 'Image not found' });
|
||||
reject(new Error('Image not found'));
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Obtenir les dimensions originales de l'image
|
||||
const resizeImage = async (imagePath) => {
|
||||
const metadata = await sharp(imagePath).metadata();
|
||||
const width = Math.floor(metadata.width / 7);
|
||||
const height = Math.floor(metadata.height / 7);
|
||||
|
||||
// Redimensionner l'image à la moitié de ses dimensions d'origine
|
||||
const resizedImage = await sharp(imagePath)
|
||||
return sharp(imagePath)
|
||||
.resize(width, height)
|
||||
.jpeg({ quality: 65 })
|
||||
.toBuffer();
|
||||
};
|
||||
|
||||
router.get('/preview/:projectId/:orderId', async (req, res) => {
|
||||
const projectId = req.params.projectId;
|
||||
const orderId = req.params.orderId;
|
||||
|
||||
try {
|
||||
const imagePath = await getImagePath(projectId, orderId);
|
||||
await checkImageExists(imagePath);
|
||||
const resizedImage = await resizeImage(imagePath);
|
||||
|
||||
res.set('Content-Type', 'image/jpeg');
|
||||
res.send(resizedImage);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error getting image preview:', err);
|
||||
if (err.message === 'Image not found') {
|
||||
return res.status(404).json({ error: 'Image not found' });
|
||||
}
|
||||
return res.status(500).json({ error: 'Internal Server Error' });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
module.exports = router;
|
||||
|
||||
Reference in New Issue
Block a user