const multer = require("multer");
const path = require("path");

const storage = multer.memoryStorage();

const filter = (req, file, cb) => {
  if (file.mimetype.split("/")[0] === "image") {
    cb(null, true);
  } else {
    cb(new Error("Only images are allowed!"));
  }
};
const whitelist = [
  "image/png",
  "image/jpeg",
  "image/jpg",
  "image/webp",
  "image/gif",
];
exports.imageUploader = multer({
  storage,
  fileFilter: function (r, file, cb) {
    const {req} = req.body;
    var ext = path.extname(file.originalname);
    if (!whitelist.includes(file.mimetype)) {
      return cb(new Error("file type is not allowed"), false);
    }
    req.on("aborted", () => {
      file.stream.on("end", () => {
        console.log("Cancel the upload");
        cb(new Error("Cancel."), false);
      });
      file.stream.emit("end");
    });
    cb(null, true);
  },
});
