Skip to content
Snippets Groups Projects
Select Git revision
  • 8ea236f05ab158564d47038b0de7b604227f3c40
  • dev default protected
  • master protected
3 results

uploadCardImage.ts

Blame
  • uploadCardImage.ts 1.23 KiB
    import { NextFunction, Request, Response } from "express";
    
    import CardImage from "../../../models/CardImageSchema";
    import File from "../../../models/FileSchema";
    import fs from "fs";
    
    /**
     * Upload a new Card background Image
     *
     * @param {Request} req
     * @param {Response} res
     * @param {NextFunction} next
     * @return {*} 200 Status code if uploaded
     */
    const uploadCardImage = () => async (
      req: Request,
      res: Response,
      next: NextFunction
    ) => {
      const oldCardImage = await CardImage.findOne().lean().exec();
    
      if (oldCardImage) {
        const oldFile = await File.findByIdAndRemove(oldCardImage.imageId)
          .lean()
          .exec();
    
        fs.unlink(oldFile!.path, (err) => {
          throw err;
        });
      }
    
      const newFile = new File();
      newFile.originalName = req.file.originalname;
      newFile.uploadDate = new Date();
      newFile.path = req.file.path;
      newFile.mimeType = req.file.mimetype;
    
      await newFile.save();
    
      if (oldCardImage) {
        await CardImage.updateOne(
          { _id: oldCardImage?.id },
          { imageId: String(newFile.id) }
        ).exec();
      } else {
        const cardImage = new CardImage();
        cardImage.imageId = String(newFile.id);
    
        await cardImage.save();
      }
    
      return res.status(200).send();
    };
    
    export default uploadCardImage;