Jelajahi Sumber

优化静态文件删除和附件表删除

shaogen1995 2 minggu lalu
induk
melakukan
81dfaef2b5

+ 11 - 21
src/controller/auditController.ts

@@ -100,6 +100,7 @@ const audit = {
 
     const deletedInfo: any = await Audit.findByIdAndDelete(_id);
     req.apiDescription = `素材审核-删除素材审核数据-${deletedInfo.title}`;
+
     return resSend(res, 0, '删除素材审核数据成功');
   },
   // 后台管理-通过id获取素材审核详情
@@ -186,6 +187,7 @@ const audit = {
             update: {
               $set: {
                 state: true,
+                disPlay: true,
                 remark: item.remark,
                 title: auditRecord.title,
                 phone: auditRecord.phone,
@@ -222,7 +224,7 @@ const audit = {
     });
   },
   // --------------------------------------
-  // 后台管理-获取素材库列表(过滤只返回state 为 true的数据)
+  // 后台管理-获取素材库列表(过滤只返回state &&disPlay为 true的数据)
   getLibraryList: async (req: any, res: any) => {
     req.apiDescription = '素材审核-获取素材库列表';
     const { pageNum = 1, pageSize = 10, searchKey = '', type = '' } = req.body;
@@ -230,6 +232,7 @@ const audit = {
     // 构建查询条件
     const query: any = {
       state: true,
+      disPlay: true,
     };
 
     if (type) query.type = type;
@@ -264,33 +267,20 @@ const audit = {
     });
   },
 
-  // 素材库-删除
+  // 素材库-删除--这里不是删除 而是把disPlay改成 false
   delLibrary: async (req: any, res: any) => {
     const { _id } = req.params; // 从URL参数中获取ID
     // 1. 根据ID查找数据
     const info = await AuditFile.findById(_id);
     if (!info) return resSend(res, 404, '_id错误或数据已被删除');
 
-    const deletedInfo: any = await AuditFile.findByIdAndDelete(_id);
+    const updatedInfo: any = await AuditFile.findByIdAndUpdate(
+      _id,
+      { $set: { disPlay: false } }, // 使用$set操作符更新disPlay字段
+      { new: true } // 返回更新后的文档
+    );
 
-    // 同时删除静态文件
-    if (deletedInfo.originalUrl) {
-      const fullOriginalPath = path.join(
-        isEnv ? process.cwd() : upStaticFileUrl,
-        '',
-        deletedInfo.originalUrl
-      );
-      deleteFileSafely(fullOriginalPath);
-    }
-    if (deletedInfo.compressedUrl) {
-      const fullOriginalPath = path.join(
-        isEnv ? process.cwd() : upStaticFileUrl,
-        '',
-        deletedInfo.compressedUrl
-      );
-      deleteFileSafely(fullOriginalPath);
-    }
-    req.apiDescription = `素材审核-删除素材库数据-${deletedInfo.title}`;
+    req.apiDescription = `素材审核-删除素材库数据-${updatedInfo.title}`;
     return resSend(res, 0, '删除素材库数据成功');
   },
 };

+ 19 - 0
src/controller/issueController.ts

@@ -2,6 +2,7 @@ import dayjs from 'dayjs';
 import { Advanced, Dict, Files, Goods, Share, Video } from '../model/index.js';
 import resSend from '../util/resSend.js';
 import { passWordJia } from '../util/pass.js';
+import { delCoverFu, deleteAttachmentsAndFiles } from '../util/delFile.js';
 
 const issue = {
   getProof: async (req: any, res: any) => {
@@ -113,6 +114,10 @@ const issue = {
     if (!info) return resSend(res, 404, '_id错误或数据已被删除');
 
     const deletedInfo: any = await Video.findByIdAndDelete(_id);
+
+    // 删除封面图视频等...
+    delCoverFu([deletedInfo.cover, deletedInfo.coverSmall, deletedInfo.videoUrl]);
+
     req.apiDescription = `内容发布-删除视频展示数据-${deletedInfo.name}`;
     return resSend(res, 0, '删除视频展示数据成功');
   },
@@ -216,6 +221,12 @@ const issue = {
     if (!info) return resSend(res, 404, '_id错误或数据已被删除');
 
     const deletedInfo: any = await Goods.findByIdAndDelete(_id);
+
+    // 删除相关附件和静态资源
+    deleteAttachmentsAndFiles(deletedInfo.fileIds, Files);
+    // 删除封面图视频等...
+    delCoverFu([deletedInfo.cover, deletedInfo.coverSmall]);
+
     req.apiDescription = `内容发布-删除展品展示数据-${deletedInfo.name}`;
     return resSend(res, 0, '删除展品展示数据成功');
   },
@@ -350,6 +361,8 @@ const issue = {
     if (!info) return resSend(res, 404, '_id错误或数据已被删除');
 
     const deletedInfo: any = await Advanced.findByIdAndDelete(_id);
+    // 删除封面图视频等...
+    delCoverFu([deletedInfo.cover, deletedInfo.coverSmall]);
     req.apiDescription = `内容发布-删除先进光源数据-${deletedInfo.name}`;
     return resSend(res, 0, '删除先进光源数据成功');
   },
@@ -447,6 +460,12 @@ const issue = {
     if (!info) return resSend(res, 404, '_id错误或数据已被删除');
 
     const deletedInfo: any = await Share.findByIdAndDelete(_id);
+
+    // 删除相关附件和静态资源
+    deleteAttachmentsAndFiles(deletedInfo.fileIds, Files);
+    // 删除封面图视频等...
+    delCoverFu([deletedInfo.cover, deletedInfo.coverSmall]);
+
     req.apiDescription = `内容发布-删除素材共享数据-${deletedInfo.name}`;
     return resSend(res, 0, '删除素材共享数据成功');
   },

+ 4 - 0
src/model/auditFileModel.ts

@@ -38,6 +38,10 @@ const auditFileSchema = new mongoose.Schema({
     type: Boolean,
     default: false,
   },
+  disPlay: {
+    type: Boolean,
+    default: false,
+  },
   // 备注
   remark: {
     type: String,

+ 4 - 2
src/util/clearAll.ts

@@ -2,7 +2,7 @@ import cron from 'node-cron';
 import fs from 'fs/promises'; // 使用 Promise 版本的 fs API
 import path from 'path';
 
-import { Audit, AuditFile, Files, Goods, Share } from '../model/index.js';
+import { Files, Goods, Share } from '../model/index.js';
 import { clearLoginCode } from '../controller/userController.js';
 import { isEnv, upStaticFileUrl, writeLogUrl } from '../config/config.default.js';
 import { AddTxtFileFu } from './index.js';
@@ -151,7 +151,9 @@ export const clearAllFu = () => {
       console.log('执行定时任务...');
       // 清理 多个集合中 有fileIds 没有使用的file文件
       clearFileFu([Goods, Share], Files);
-      clearFileFu([Audit], AuditFile);
+
+      // 这个表不应该删除,他们是相互独立的 其中一个被删了 另外一个的数据还在
+      // clearFileFu([Audit], AuditFile);
       // 清理用户登录的验证码对象
       clearLoginCode();
       clearAuditCode();

+ 107 - 0
src/util/delFile.ts

@@ -0,0 +1,107 @@
+import path from 'path';
+import { isEnv, upStaticFileUrl } from '../config/config.default.js';
+import { deleteFileSafely } from './clearAll.js';
+
+/**
+ * 批量删除附件表数据及相关的静态资源文件
+ * @param {Array<string>} idArray - 附件ID数组,可能为null或空数组
+ * @param {myModel} options - 要删除的附件表
+ * @returns {Object} 删除结果对象
+ */
+export async function deleteAttachmentsAndFiles(idArray: string[], myModel: any) {
+  // 参数验证:如果idArray为null或空数组,直接返回
+  if (!idArray || idArray.length === 0) {
+    return {
+      success: true,
+      message: 'ID数组为空,无需执行删除操作',
+      deletedCount: 0,
+      deletedFiles: [],
+    };
+  }
+
+  try {
+    // 1. 查询匹配的附件数据
+    const filesToDelete = await myModel.find({
+      _id: { $in: idArray },
+    });
+
+    if (filesToDelete.length === 0) {
+      return {
+        success: true,
+        message: '未找到匹配的附件数据',
+        deletedCount: 0,
+        deletedFiles: [],
+      };
+    }
+
+    // 2. 批量删除数据库记录
+    const deleteResult = await myModel.deleteMany({
+      _id: { $in: idArray },
+    });
+
+    // 3. 删除相关的静态资源文件
+    const deletedFilePaths = [];
+
+    for (const fileInfo of filesToDelete) {
+      try {
+        // 删除原始文件
+        if (fileInfo.originalUrl) {
+          const fullOriginalPath = path.join(
+            isEnv ? process.cwd() : upStaticFileUrl,
+            '',
+            fileInfo.originalUrl
+          );
+          await deleteFileSafely(fullOriginalPath);
+          deletedFilePaths.push(fullOriginalPath);
+        }
+
+        // 删除压缩文件
+        if (fileInfo.compressedUrl) {
+          const fullCompressedPath = path.join(
+            isEnv ? process.cwd() : upStaticFileUrl,
+            '',
+            fileInfo.compressedUrl
+          );
+          await deleteFileSafely(fullCompressedPath);
+          deletedFilePaths.push(fullCompressedPath);
+        }
+      } catch (fileError) {
+        console.error(`删除文件 ${fileInfo._id} 的静态资源失败:`, fileError);
+        // 继续处理其他文件,不中断整个流程
+      }
+    }
+
+    return {
+      success: true,
+      message: `成功删除 ${deleteResult.deletedCount} 条附件记录及相关静态文件`,
+      deletedCount: deleteResult.deletedCount,
+      deletedFiles: deletedFilePaths,
+      deletedIds: filesToDelete.map((file: any) => file._id),
+    };
+  } catch (error: any) {
+    console.error('删除附件及文件过程中发生错误:', error);
+    return {
+      success: false,
+      message: `删除操作失败: ${error.message}`,
+      deletedCount: 0,
+      deletedFiles: [],
+      error: error.message,
+    };
+  }
+}
+
+// 删除封面图视频等静态资源
+export const delCoverFu = async (fileUrlArr: string[]) => {
+  for (const url of fileUrlArr) {
+    try {
+      // 删除原始文件
+      if (url) {
+        const fullOriginalPath = path.join(isEnv ? process.cwd() : upStaticFileUrl, '', url);
+        await deleteFileSafely(fullOriginalPath);
+      }
+    } catch (fileError) {
+      console.error(`删除文件 ${url} 的静态资源失败:`, fileError);
+      // 继续处理其他文件,不中断整个流程
+    }
+  }
+};