file upload and store
This commit is contained in:
@@ -4,10 +4,12 @@ const path = require("path");
|
||||
const fs = require("fs");
|
||||
const multer = require("multer");
|
||||
const defineAttachment = require("../../models/attachments");
|
||||
const defineCaseAttachment = require("../../models/caseAttachments");
|
||||
const { DataTypes } = require("sequelize");
|
||||
|
||||
module.exports = function (sequelize) {
|
||||
const Attachment = defineAttachment(sequelize, DataTypes);
|
||||
const CaseAttachment = defineCaseAttachment(sequelize, DataTypes);
|
||||
|
||||
// Create uploads folder if it does not exist
|
||||
const uploadDir = path.join(__dirname, "../../public/uploads");
|
||||
@@ -45,7 +47,9 @@ module.exports = function (sequelize) {
|
||||
const upload = multer({ storage });
|
||||
|
||||
router.post("/", upload.array("files", 10), async (req, res) => {
|
||||
const t = await sequelize.transaction();
|
||||
try {
|
||||
const caseId = req.query.parentCaseId;
|
||||
const files = req.files;
|
||||
if (files.length === 0) {
|
||||
return res.status(400).json({ error: "No files uploaded" });
|
||||
@@ -58,10 +62,19 @@ module.exports = function (sequelize) {
|
||||
path: `${protocol}://${host}/uploads/${file.filename}`,
|
||||
}));
|
||||
|
||||
const newAttachments = await Attachment.bulkCreate(attachmentsData);
|
||||
const newAttachments = await Attachment.bulkCreate(attachmentsData, {
|
||||
transaction: t,
|
||||
});
|
||||
|
||||
const caseAttachmentsData = newAttachments.map((attachment) => ({
|
||||
caseId: caseId,
|
||||
attachmentId: attachment.id,
|
||||
}));
|
||||
await CaseAttachment.bulkCreate(caseAttachmentsData, { transaction: t });
|
||||
await t.commit();
|
||||
res.json(newAttachments);
|
||||
} catch (error) {
|
||||
await t.rollback();
|
||||
res.status(500).json({ error: "Internal server error" });
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user