EvalueTonSavoir/server/controllers/images.js

57 lines
1.6 KiB
JavaScript
Raw Normal View History

2024-03-29 20:08:34 -04:00
const AppError = require('../middleware/AppError.js');
2024-04-05 20:10:59 -04:00
const { MISSING_REQUIRED_PARAMETER, IMAGE_NOT_FOUND } = require('../constants/errorCodes');
2024-03-29 20:08:34 -04:00
class ImagesController {
constructor(imagesModel) {
this.images = imagesModel;
console.log("ImagesController constructor: images", this.images);
}
upload = async (req, res, next) => {
2024-03-29 20:08:34 -04:00
try {
const file = req.file;
2024-03-29 20:08:34 -04:00
if (!file) {
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
const id = await this.images.upload(file, req.user.userId);
2024-03-29 20:08:34 -04:00
return res.status(200).json({
id: id
});
} catch (error) {
2024-03-29 20:08:34 -04:00
return next(error);
}
};
get = async (req, res, next) => {
2024-03-29 20:08:34 -04:00
try {
const { id } = req.params;
2024-03-29 20:08:34 -04:00
if (!id) {
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
const image = await this.images.get(id);
2024-03-29 20:08:34 -04:00
if (!image) {
throw new AppError(IMAGE_NOT_FOUND);
2024-03-29 20:08:34 -04:00
}
2024-03-29 20:08:34 -04:00
// Set Headers for display in browser
res.setHeader('Content-Type', image.mime_type);
res.setHeader('Content-Disposition', 'inline; filename=' + image.file_name);
res.setHeader('Accept-Ranges', 'bytes');
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
return res.send(image.file_content);
} catch (error) {
2024-03-29 20:08:34 -04:00
return next(error);
}
};
2024-03-29 20:08:34 -04:00
}
module.exports = ImagesController;