Home > Back-end >  what to do with image in case later part of code fails in multer nodejs
what to do with image in case later part of code fails in multer nodejs

Time:08-08

I am using multer to store book covers in my server but the thing is multer is a middleware it will first save image in my server and then will carry on with later part of code which is storing book info in my database.

And in case book creation fails (because of wrong title or isbn or error) then I am left with a copy of image uploaded. So, what should I do with it.

Here's a copy of my code which handles this part. router code to handle request from client

const router = require('express').Router();
const multer = require('multer');

const createBook = require('../controller/createBook');
const { auth } = require('../middleware/authHandler');

const routePlan = require('../route_plan');
const renderFilePath = routePlan.createBook[2];
const redirectUrl = routePlan.createBook[0]

const upload = multer({
    dest: 'public/bookCover/',
    limits: {
        fileSize: 10 * 1024 * 1024,
    },
    fileFilter(req, file, cb) {
        if (!file.originalname.match(/\.(png|jpg|jpeg)$/)) {
            cb(new Error('Please upload an image.'))
        }
        cb(undefined, true)
    }
});

router.use(auth);

router.get('/', async(req, res) => {
    res.render(renderFilePath, { post_to: redirectUrl });
});

router.post('/', upload.single('bookCover'), createBook);

module.exports = router;

controller code to create book

const { Book, JoiValidBook } = require('../models/book');
const { User } = require('../models/user');


//create Book after validation returns true.
async function createBook(req, res){
    const validBook = req.validatedBook;

    let book = new Book(validBook);
    book = await book.save();

    await User.findOneAndUpdate(
        { _id: req.user._id },
        { $push: { book_id: book._id } });

    res.send({ msg: "Congrats your book has been published on our website!!! " });
}

//isbn validatipon
function checkISBN(isbn){
    //code for checking isbn return true for valid else false
}

//takes data posted and form it in a readable format
//then validate/sanitize it against schema
//if error arises or book already exists a msg is passed on
//else book creation process is executed 
module.exports = async function(req, res){
    let book = {
        img: req.file?.path,
        title: req.body.title,
        isbn: req.body.isbn,
        author_name: req.user.username,
        summary: "Summary need to be updated plz check after sometime",
        pub_date: new Date()
    };

    const { err } = JoiValidBook.validate(book);
    if (err) {
        res.status(406);
        return res.render('error', { message: err.details[0].message });
    } else {
        const ExistBook = await Book.findOne({
            $or: [
                { title: book.title },
                { isbn: book.isbn }
            ]
        });

        if (ExistBook) return res.status(400).render('error', {
            message: "It Seems book with same title or isbn already exists"
        });

        if(!checkISBN(book.isbn)) return res.render('error', {
            message: "Plz Enter valid isbn number!!!"
        });
        
        req.validatedBook = book;
        createBook(req, res);
    }
};

CodePudding user response:

Hi at the time of uploading the file if something failed. You can add a checker 
if failed then check the file in path and delete it.
you can put delete file code in if(err) section.
  • Related