Răsfoiți Sursa

refactor attachments.remove api

Yuki Takei 7 ani în urmă
părinte
comite
0468a4474e

+ 4 - 4
src/server/models/attachment.js

@@ -74,7 +74,7 @@ module.exports = function(crowi) {
       Attachment.find({ page: pageId})
       .then((attachments) => {
         for (let attachment of attachments) {
-          Attachment.removeWithSubstance(attachment).then((res) => {
+          Attachment.removeWithSubstanceById(attachment._id).then((res) => {
             // do nothing
           }).catch((err) => {
             debug('Attachment remove error', err);
@@ -89,11 +89,11 @@ module.exports = function(crowi) {
 
   };
 
-  attachmentSchema.statics.removeWithSubstance = async function(attachment) {
+  attachmentSchema.statics.removeWithSubstanceById = async function(id) {
     // retrieve data from DB
     // because this instance fields are only partially populated
-    const att = await this.findById(attachment._id);
-    await fileUploader.deleteFile(att);
+    const attachment = await this.findById(id);
+    await fileUploader.deleteFile(attachment);
     return await this.remove();
   };
 

+ 1 - 1
src/server/models/user.js

@@ -221,7 +221,7 @@ module.exports = function(crowi) {
     this.image = undefined;
 
     if (this.imageAttachment != null) {
-      Attachment.removeWithSubstance(this.imageAttachment);
+      Attachment.removeWithSubstance(this.imageAttachment._id);
     }
 
     this.imageAttachment = undefined;

+ 9 - 17
src/server/routes/attachment.js

@@ -283,25 +283,17 @@ module.exports = function(crowi, app) {
    *
    * @apiParam {String} attachment_id
    */
-  api.remove = function(req, res) {
+  api.remove = async function(req, res) {
     const id = req.body.attachment_id;
 
-    Attachment.findById(id)
-    .then(function(data) {
-      const attachment = data;
-
-      attachment.removeWithSubstance()
-      .then(data => {
-        debug('removeAttachment', data);
-        return res.json(ApiResponse.success({}));
-      }).catch(err => {
-        logger.error('Error', err);
-        return res.status(500).json(ApiResponse.error('Error while deleting file'));
-      });
-    }).catch(err => {
-      logger.error('Error', err);
-      return res.status(404);
-    });
+    try {
+      await Attachment.removeWithSubstanceById(id);
+    }
+    catch (err) {
+      return res.status(500).json(ApiResponse.error('Error while deleting file'));
+    }
+
+    return res.json(ApiResponse.success({}));
   };
 
   return actions;