Skip to content

Commit

Permalink
file upload added
Browse files Browse the repository at this point in the history
  • Loading branch information
Klerith committed Feb 10, 2021
1 parent 1bb8231 commit 61454a2
Show file tree
Hide file tree
Showing 15 changed files with 391 additions and 6 deletions.
5 changes: 4 additions & 1 deletion .example.env
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,7 @@ SECRETORPRIVATEKEY=


GOOGLE_CLIENT_ID=
GOOGLE_SECRET_ID=
GOOGLE_SECRET_ID=


CLOUDINARY_URL=
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@

node_modules/

.env
.env

uploads/productos/**.*
uploads/usuarios/**.*
Binary file added assets/no-image.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
188 changes: 188 additions & 0 deletions controllers/uploads.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
const path = require('path');
const fs = require('fs');

const cloudinary = require('cloudinary').v2
cloudinary.config( process.env.CLOUDINARY_URL );

const { response } = require('express');
const { subirArchivo } = require('../helpers');

const { Usuario, Producto } = require('../models');


const cargarArchivo = async(req, res = response) => {


try {

// txt, md
// const nombre = await subirArchivo( req.files, ['txt','md'], 'textos' );
const nombre = await subirArchivo( req.files, undefined, 'imgs' );
res.json({ nombre });

} catch (msg) {
res.status(400).json({ msg });
}

}


const actualizarImagen = async(req, res = response ) => {

const { id, coleccion } = req.params;

let modelo;

switch ( coleccion ) {
case 'usuarios':
modelo = await Usuario.findById(id);
if ( !modelo ) {
return res.status(400).json({
msg: `No existe un usuario con el id ${ id }`
});
}

break;

case 'productos':
modelo = await Producto.findById(id);
if ( !modelo ) {
return res.status(400).json({
msg: `No existe un producto con el id ${ id }`
});
}

break;

default:
return res.status(500).json({ msg: 'Se me olvidó validar esto'});
}


// Limpiar imágenes previas
if ( modelo.img ) {
// Hay que borrar la imagen del servidor
const pathImagen = path.join( __dirname, '../uploads', coleccion, modelo.img );
if ( fs.existsSync( pathImagen ) ) {
fs.unlinkSync( pathImagen );
}
}


const nombre = await subirArchivo( req.files, undefined, coleccion );
modelo.img = nombre;

await modelo.save();


res.json( modelo );

}


const actualizarImagenCloudinary = async(req, res = response ) => {

const { id, coleccion } = req.params;

let modelo;

switch ( coleccion ) {
case 'usuarios':
modelo = await Usuario.findById(id);
if ( !modelo ) {
return res.status(400).json({
msg: `No existe un usuario con el id ${ id }`
});
}

break;

case 'productos':
modelo = await Producto.findById(id);
if ( !modelo ) {
return res.status(400).json({
msg: `No existe un producto con el id ${ id }`
});
}

break;

default:
return res.status(500).json({ msg: 'Se me olvidó validar esto'});
}


// Limpiar imágenes previas
if ( modelo.img ) {
const nombreArr = modelo.img.split('/');
const nombre = nombreArr[ nombreArr.length - 1 ];
const [ public_id ] = nombre.split('.');
cloudinary.uploader.destroy( public_id );
}


const { tempFilePath } = req.files.archivo
const { secure_url } = await cloudinary.uploader.upload( tempFilePath );
modelo.img = secure_url;

await modelo.save();


res.json( modelo );

}

const mostrarImagen = async(req, res = response ) => {

const { id, coleccion } = req.params;

let modelo;

switch ( coleccion ) {
case 'usuarios':
modelo = await Usuario.findById(id);
if ( !modelo ) {
return res.status(400).json({
msg: `No existe un usuario con el id ${ id }`
});
}

break;

case 'productos':
modelo = await Producto.findById(id);
if ( !modelo ) {
return res.status(400).json({
msg: `No existe un producto con el id ${ id }`
});
}

break;

default:
return res.status(500).json({ msg: 'Se me olvidó validar esto'});
}


// Limpiar imágenes previas
if ( modelo.img ) {
// Hay que borrar la imagen del servidor
const pathImagen = path.join( __dirname, '../uploads', coleccion, modelo.img );
if ( fs.existsSync( pathImagen ) ) {
return res.sendFile( pathImagen )
}
}

const pathImagen = path.join( __dirname, '../assets/no-image.jpg');
res.sendFile( pathImagen );
}




module.exports = {
cargarArchivo,
actualizarImagen,
mostrarImagen,
actualizarImagenCloudinary
}
15 changes: 14 additions & 1 deletion helpers/db-validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,25 @@ const existeProductoPorId = async( id ) => {
}
}

/**
* Validar colecciones permitidas
*/
const coleccionesPermitidas = ( coleccion = '', colecciones = []) => {

const incluida = colecciones.includes( coleccion );
if ( !incluida ) {
throw new Error(`La colección ${ coleccion } no es permitida, ${ colecciones }`);
}
return true;
}


module.exports = {
esRoleValido,
emailExiste,
existeUsuarioPorId,
existeCategoriaPorId,
existeProductoPorId
existeProductoPorId,
coleccionesPermitidas
}

14 changes: 14 additions & 0 deletions helpers/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@


const dbValidators = require('./db-validators');
const generarJWT = require('./generar-jwt');
const googleVerify = require('./google-verify');
const subirArchivo = require('./subir-archivo');


module.exports = {
...dbValidators,
...generarJWT,
...googleVerify,
...subirArchivo,
}
36 changes: 36 additions & 0 deletions helpers/subir-archivo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const path = require('path');
const { v4: uuidv4 } = require('uuid');

const subirArchivo = ( files, extensionesValidas = ['png','jpg','jpeg','gif'], carpeta = '' ) => {

return new Promise( (resolve, reject) => {

const { archivo } = files;
const nombreCortado = archivo.name.split('.');
const extension = nombreCortado[ nombreCortado.length - 1 ];

// Validar la extension
if ( !extensionesValidas.includes( extension ) ) {
return reject(`La extensión ${ extension } no es permitida - ${ extensionesValidas }`);
}

const nombreTemp = uuidv4() + '.' + extension;
const uploadPath = path.join( __dirname, '../uploads/', carpeta, nombreTemp );

archivo.mv(uploadPath, (err) => {
if (err) {
reject(err);
}

resolve( nombreTemp );
});

});

}



module.exports = {
subirArchivo
}
6 changes: 4 additions & 2 deletions middlewares/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@


const validaCampos = require('../middlewares/validar-campos');
const validarJWT = require('../middlewares/validar-jwt');
const validaRoles = require('../middlewares/validar-roles');
const validarJWT = require('../middlewares/validar-jwt');
const validaRoles = require('../middlewares/validar-roles');
const validarArchivo = require('../middlewares/validar-archivo');

module.exports = {
...validaCampos,
...validarJWT,
...validaRoles,
...validarArchivo
}
19 changes: 19 additions & 0 deletions middlewares/validar-archivo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const { response } = require("express")


const validarArchivoSubir = (req, res = response, next ) => {

if (!req.files || Object.keys(req.files).length === 0 || !req.files.archivo ) {
return res.status(400).json({
msg: 'No hay archivos que subir - validarArchivoSubir'
});
}

next();

}


module.exports = {
validarArchivoSubir
}
1 change: 1 addition & 0 deletions models/producto.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const ProductoSchema = Schema({
},
descripcion: { type: String },
disponible: { type: Boolean, defult: true },
img: { type: String },
});


Expand Down
11 changes: 11 additions & 0 deletions models/server.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const express = require('express');
const cors = require('cors');
const fileUpload = require('express-fileupload');

const { dbConnection } = require('../database/config');

Expand All @@ -15,6 +16,7 @@ class Server {
categorias: '/api/categorias',
productos: '/api/productos',
usuarios: '/api/usuarios',
uploads: '/api/uploads',
}


Expand Down Expand Up @@ -44,6 +46,13 @@ class Server {
// Directorio Público
this.app.use( express.static('public') );

// Fileupload - Carga de archivos
this.app.use( fileUpload({
useTempFiles : true,
tempFileDir : '/tmp/',
createParentPath: true
}));

}

routes() {
Expand All @@ -53,6 +62,8 @@ class Server {
this.app.use( this.paths.categorias, require('../routes/categorias'));
this.app.use( this.paths.productos, require('../routes/productos'));
this.app.use( this.paths.usuarios, require('../routes/usuarios'));
this.app.use( this.paths.uploads, require('../routes/uploads'));

}

listen() {
Expand Down
Loading

0 comments on commit 61454a2

Please sign in to comment.