How can I validate the multer so that it does not save the image in the Storage if the database validation returns false?

Asked

Viewed 39 times

0

const multer = require('multer');
const path = require('path');
const crypto = require('crypto');
const aws = require('aws-sdk')
const multerS3 = require('multer-s3');
const s3 = new aws.S3();

const local = multer.diskStorage({
    dest: path.resolve(__dirname, '..', '..', 'temp', 'uploads'),
    destination: (req, file, cb) => { cb(null, path.resolve(__dirname, '..', '..', 'temp', 'uploads')) },

    filename: (req, file, cb) => {
        crypto.randomBytes(16, (err, hash) => {
            if (err) cb(err)
            file.key = `${hash.toString("hex")}-${file.originalname}`
            cb(null, file.key)
        })
    }
});


const s3aws = multerS3({
    s3:s3,
    bucket: process.env.BUCKET_NAME,
    contentType: multerS3.AUTO_CONTENT_TYPE,
    acl: 'public-read',
    key: (req, file, cb) => {
        crypto.randomBytes(16, (err, hash) => {
            if (err) cb(err)
            const fileName = `${hash.toString("hex")}-${file.originalname}`
            cb(null, fileName)
        })
    }
});

const limits = {
    fileSize: 2 * 1024 * 1024,
};
const fileFilter = async(req, file, cb) => {
    const allowedMimes = [
        'image/jpeg',
        'image/pjpeg',
        'image/png',
        'image/gif'
    ];

    if (allowedMimes.includes(file.mimetype)) {
        cb(null, true);
    } else {
        cb(new Error('invalid file type'));
    }
};

const storageTypes ={
    local:local,
    s3:s3aws,
}

const upload = multer({
    storage: storageTypes[process.env.STORAGE_TYPE],
    limits: limits,
    fileFilter: fileFilter,
});

module.exports = upload

const Product =require('../models/products.model');


module.exports = {

    async index(req, res) {
        const product = await Product.find()
        res.json(product);
    },
    async create(req, res) {
        console.log(req)
        const{location:url="", key:key} = req.file
        const {product_name, product_nameStore, product_storeLink, product_shippingCostReceiver, product_shippingCostSend, product_priceTax, product_myStoreLink, product_priceBuy, product_priceSale, product_avaibleSize, product_myStoreAvaibleSize,} = req.body;
        product_image = await url;
        let data = {};
        let product = await Product.findOne({product_name});
        if(!product){
            data = {product_name, product_nameStore, product_storeLink, product_shippingCostReceiver, product_shippingCostSend, product_priceTax, product_myStoreLink, product_priceBuy, product_priceSale, product_avaibleSize, product_myStoreAvaibleSize, product_image, key};
            product = await Product.create(data);
            return res.status(200).json(product);
        }else{
            return res.status(500).json(product)
        }
    },
    async id(req, res) {
        const {_id} = req.params;
        const product = await Product.findOne({_id});
        res.json(product);
    },
    async delete(req, res){
        const{_id} = req.params;
        const product = await Product.findById(_id)
        await product.remove()
        return res.json(product)
    },

    async update(req, res){
        const {_id, product_name, product_nameStore, product_storeLink, product_shippingCostReceiver, product_shippingCostSend, product_priceTax, product_myStoreLink, product_priceBuy, product_priceSale, product_avaibleSize, product_myStoreAvaibleSize} = req.body;
        const data = {product_name, product_nameStore, product_storeLink, product_shippingCostReceiver, product_shippingCostSend, product_priceTax, product_myStoreLink, product_priceBuy, product_priceSale, product_avaibleSize, product_myStoreAvaibleSize};
        const product = await Product.findOneAndUpdate({_id},data,{new:true});
        res.json(product);
    },
    async jdsports(req, res) {
        const product = await Product.find({product_nameStore:"jdsports"})
        res.json(product);
    },
    async asos(req, res) {
        const product = await Product.find({product_nameStore:"asos"})
        res.json(product);
    },
}
const express = require('express')
const routes = express.Router()
const Users = require('./controllers/users.controllers')
const Products = require('./controllers/products.controllers')
const upload = require('./config/multer')



// Routes Users
routes.get('/api/users', Users.index);
routes.get('/api/users/:_id', Users.id);
routes.post('/api/users', Users.create);
routes.delete('/api/users/:_id', Users.delete);
routes.put('/api/users', Users.update);


//Routes Products
routes.get('/api/products', Products.index);
routes.get('/api/products/:_id', Products.id);
routes.post('/api/products', upload.single("file"), Products.create);
routes.delete('/api/products/:_id', Products.delete);
routes.put('/api/products', Products.update);
routes.get('/api/jdsports', Products.jdsports);
routes.get('/api/asos', Products.asos);

module.exports = routes; 
  • What kind of validation? If the product already exists in the database, do not save the upload file?

  • that’s right ! sorry my ignorance is that I’m well Noob yet !

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.