Select Git revision
uploadCardImage.ts

Rafael László authored
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;