EvalueTonSavoir/server/controllers/images.js

91 lines
2.7 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;
}
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
2025-02-24 20:26:30 -05:00
getImages = async (req, res, next) => {
2025-02-22 17:56:53 -05:00
try {
2025-02-24 20:26:30 -05:00
const page = parseInt(req.query.page) || 1;
2025-03-04 19:49:18 -05:00
const limit = parseInt(req.query.limit) || 5;
const images = await this.images.getImages(page, limit);
2025-02-22 17:56:53 -05:00
if (!images || images.length === 0) {
throw new AppError(IMAGE_NOT_FOUND);
}
res.setHeader('Content-Type', 'application/json');
return res.status(200).json(images);
} catch (error) {
return next(error);
}
};
getUserImages = async (req, res, next) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 5;
const uid = req.query.uid;
const images = await this.images.getUserImages(page, limit, uid);
2025-02-22 17:56:53 -05:00
if (!images || images.length === 0) {
2025-02-22 17:56:53 -05:00
throw new AppError(IMAGE_NOT_FOUND);
}
res.setHeader('Content-Type', 'application/json');
return res.status(200).json(images);
2025-02-22 17:56:53 -05:00
} catch (error) {
return next(error);
}
};
2024-03-29 20:08:34 -04:00
}
module.exports = ImagesController;