delete uploaded file

This commit is contained in:
Takeshi Kimata
2024-03-17 20:15:54 +09:00
parent d94af046c0
commit 1825545bf0
4 changed files with 87 additions and 2 deletions

View File

@@ -63,7 +63,9 @@ app.use("/steps", stepsDeleteRoute);
// "/attachments"
const attachmentsNewRoute = require("./routes/attachments/new")(sequelize);
const attachmentsDeleteRoute = require("./routes/attachments/delete")(sequelize);
app.use("/attachments", attachmentsNewRoute);
app.use("/attachments", attachmentsDeleteRoute);
// "/runs"
const runsIndexRoute = require("./routes/runs/index")(sequelize);

View File

@@ -0,0 +1,47 @@
const express = require("express");
const router = express.Router();
const path = require("path");
const fs = require("fs");
const defineAttachment = require("../../models/attachments");
const { DataTypes } = require("sequelize");
module.exports = function (sequelize) {
const Attachment = defineAttachment(sequelize, DataTypes);
router.delete("/:attachmentId", async (req, res) => {
const attachmentId = req.params.attachmentId;
const t = await sequelize.transaction();
try {
const attachment = await Attachment.findByPk(attachmentId);
if (!attachment) {
await t.rollback();
return res.status(404).send("Attachment not found");
}
// delete file from folder
const uploadDir = path.join(__dirname, "../../public");
const url = attachment.path;
const parts = url.split('/');
const fileNameWithFolder = parts.slice(-2).join('/');
const filePath = path.join(uploadDir, fileNameWithFolder);
fs.unlink(filePath, (err) => {
if (err) {
console.error('Error deleting file:', err);
t.rollback();
return res.status(404).send("Attachment not found");
}
});
await attachment.destroy({ transaction: t });
await t.commit();
res.status(204).send();
} catch (error) {
console.error(error);
await t.rollback();
res.status(500).send("Internal Server Error");
}
});
return router;
};