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 {
|
|
|
|
|
|
2024-10-02 10:23:56 -04:00
|
|
|
constructor(imagesModel) {
|
|
|
|
|
this.images = imagesModel;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
upload = async (req, res, next) => {
|
2024-03-29 20:08:34 -04:00
|
|
|
try {
|
|
|
|
|
const file = req.file;
|
2024-10-02 10:23:56 -04:00
|
|
|
|
2024-03-29 20:08:34 -04:00
|
|
|
if (!file) {
|
|
|
|
|
throw new AppError(MISSING_REQUIRED_PARAMETER);
|
|
|
|
|
}
|
2024-10-02 10:23:56 -04:00
|
|
|
|
|
|
|
|
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
|
|
|
|
|
});
|
2024-10-02 10:23:56 -04:00
|
|
|
} catch (error) {
|
2024-03-29 20:08:34 -04:00
|
|
|
return next(error);
|
|
|
|
|
}
|
2024-10-02 10:23:56 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
get = async (req, res, next) => {
|
2024-03-29 20:08:34 -04:00
|
|
|
try {
|
|
|
|
|
const { id } = req.params;
|
2024-10-02 10:23:56 -04:00
|
|
|
|
2024-03-29 20:08:34 -04:00
|
|
|
if (!id) {
|
|
|
|
|
throw new AppError(MISSING_REQUIRED_PARAMETER);
|
|
|
|
|
}
|
2024-10-02 10:23:56 -04:00
|
|
|
|
|
|
|
|
const image = await this.images.get(id);
|
|
|
|
|
|
2024-03-29 20:08:34 -04:00
|
|
|
if (!image) {
|
2024-10-02 10:23:56 -04:00
|
|
|
throw new AppError(IMAGE_NOT_FOUND);
|
2024-03-29 20:08:34 -04:00
|
|
|
}
|
2024-10-02 10:23:56 -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);
|
2024-10-02 10:23:56 -04:00
|
|
|
} catch (error) {
|
2024-03-29 20:08:34 -04:00
|
|
|
return next(error);
|
|
|
|
|
}
|
2024-10-02 10:23:56 -04:00
|
|
|
};
|
2024-03-29 20:08:34 -04:00
|
|
|
|
2025-02-22 17:56:53 -05:00
|
|
|
//TODO TEST
|
|
|
|
|
getAll = async (req, res, next) => {
|
|
|
|
|
try {
|
|
|
|
|
|
|
|
|
|
const images = await this.images.getAll();
|
|
|
|
|
|
|
|
|
|
if (!images || images.length === 0) {
|
|
|
|
|
throw new AppError(IMAGE_NOT_FOUND);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
res.setHeader('Content-Type', 'application/json');
|
|
|
|
|
return res.status(200).json(imagesName);
|
|
|
|
|
} catch (error) {
|
|
|
|
|
return next(error);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2024-03-29 20:08:34 -04:00
|
|
|
}
|
|
|
|
|
|
2024-10-02 10:23:56 -04:00
|
|
|
module.exports = ImagesController;
|