Files
unocial-api/routes/posts.js
2025-11-04 00:40:51 -06:00

100 lines
3.1 KiB
JavaScript

import { Router } from 'express';
import { createNewPost, getPostById, deletePost, getAllPosts, getPostsByUserId, editPost } from '../functions/postFunctions.js';
const router = Router();
import path from 'path';
import multer from 'multer';
import fs from 'fs/promises';
import sharp from 'sharp';
import crypto from 'crypto';
import { fileTypeFromBuffer } from 'file-type';
/*const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
}
});*/
const storage = multer.memoryStorage();
const fileFilter = (req, file, cb) => {
if (file.mimetype.startsWith('image/')) {
cb(null, true);
} else {
cb(new Error('Solo se permiten imágenes'), false);
}
};
const upload = multer({
storage: storage,
fileFilter: fileFilter,
limits: {
fileSize: 5 * 1024 * 1024 // 5MB limit
}
});
async function processImage(file) {
const imagePath = path.join(process.cwd(), 'uploads');
const buffer = file.buffer;
const hash = crypto.createHash('sha256').update(buffer).digest('hex');
const mime = await fileTypeFromBuffer(buffer).then(type => type?.mime);
// Validate MIME type
if (!mime || !['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(mime)) {
throw new Error('Unsupported image format');
}
// File save name and path if not GIF
let filename;
if (mime === 'image/gif') {
filename = `${hash}.gif`;
await fs.writeFile(path.join(imagePath, filename), buffer);
} else {
filename = `${hash}.webp`;
await sharp(buffer)
.resize({ width: 800, height: 800, fit: 'inside', withoutEnlargement: true })
.rotate()
.normalise()
.withMetadata()
.toFormat('webp', { quality: 80 })
.toFile(path.join(imagePath, filename));
}
return filename;
}
const processUploadedImage = async (req, res, next) => {
try {
if (req.file) {
const filename = await processImage(req.file);
req.processedFilename = filename;
}
next();
} catch (error) {
console.error('Error processing image:', error);
res.status(400).json({ error: 'Error al procesar la imagen: ' + error.message });
}
};
// Validate post creation payload
const validatePostPayload = (req, res, next) => {
const { contenido, id_usuario } = req.body;
if (!contenido || !id_usuario) {
return res.status(400).json({ error: 'contenido and id_usuario are required' });
}
next();
};
router.post('/', upload.single('imagen'), validatePostPayload, processUploadedImage, createNewPost);
router.get('/:id_post', getPostById);
router.delete('/:id_post', deletePost);
router.get('/', getAllPosts);
router.get('/comunities/:comunity', getPostById);
router.get('/user/:userId', getPostsByUserId);
router.put('/:id_post', editPost);
export default router;