API Migrada
This commit is contained in:
19
routes/api.js
Normal file
19
routes/api.js
Normal file
@@ -0,0 +1,19 @@
|
||||
import { Router } from 'express';
|
||||
import { createNewUser, validateForUser } from '../functions/userFunctions.js';
|
||||
|
||||
|
||||
const router = Router();
|
||||
router.get('/', async (req, res) => {
|
||||
res.send({ Status: `Running` });
|
||||
console.log(`${req.ip} - ${req.baseUrl}${req.url}: ${res.statusCode}, ${res.statusMessage}`);
|
||||
});
|
||||
|
||||
router.post('/signup', createNewUser);
|
||||
router.post('/login', validateForUser);
|
||||
|
||||
router.post('/logout', (req,res) => {
|
||||
res.send({ message: "logout endpoint" });
|
||||
console.log(`${req.ip} - ${req.baseUrl}${req.url}: ${res.statusCode}, ${res.statusMessage}`);
|
||||
});
|
||||
|
||||
export default router;
|
||||
22
routes/comments.js
Normal file
22
routes/comments.js
Normal file
@@ -0,0 +1,22 @@
|
||||
import { Router } from 'express';
|
||||
import { createNewComment, getCommentsByPostId, deleteComment, getAllComments, getCommentById, editComment } from '../functions/commentFunctions.js';
|
||||
const router = Router();
|
||||
|
||||
// Validate create comment payload
|
||||
const validateCommentPayload = (req, res, next) => {
|
||||
// ...simple validation...
|
||||
const { contenido, id_usuario, id_post } = req.body;
|
||||
if (!contenido || !id_usuario || !id_post) {
|
||||
return res.status(400).json({ error: 'contenido, id_usuario and id_post are required' });
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
router.post('/', validateCommentPayload, createNewComment);
|
||||
router.get('/', getAllComments);
|
||||
router.get('/post/:id_post', getCommentsByPostId);
|
||||
router.get('/:id_comentario', getCommentById);
|
||||
router.put('/:id_comentario', editComment);
|
||||
router.delete('/:id_comentario', deleteComment);
|
||||
|
||||
export default router;
|
||||
10
routes/index.js
Normal file
10
routes/index.js
Normal file
@@ -0,0 +1,10 @@
|
||||
import { Router } from 'express';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
res.send({ RESPONSE: "This is the API's base route. This is a testing thing." });
|
||||
console.log(`HTTP RESPONSE: ${res.statusCode}, ${res.statusMessage}`);
|
||||
});
|
||||
|
||||
export default router;
|
||||
98
routes/posts.js
Normal file
98
routes/posts.js
Normal file
@@ -0,0 +1,98 @@
|
||||
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('/user/:userId', getPostsByUserId);
|
||||
router.put('/:id_post', editPost);
|
||||
|
||||
export default router;
|
||||
15
routes/user.js
Normal file
15
routes/user.js
Normal file
@@ -0,0 +1,15 @@
|
||||
import { Router } from 'express';
|
||||
import { editUser, getAllUsers, getSpecificUser, deleteUser } from '../functions/userFunctions.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.get('/:userId', getSpecificUser);
|
||||
|
||||
router.patch('/:userId', editUser);
|
||||
|
||||
router.get('/', getAllUsers);
|
||||
|
||||
router.delete('/:userId', deleteUser);
|
||||
|
||||
|
||||
export default router;
|
||||
Reference in New Issue
Block a user