Просмотр исходного кода

Refactor attachment creation to handle attached handlers asynchronously

Shun Miyazawa 11 месяцев назад
Родитель
Сommit
749e2af726
1 измененных файлов с 13 добавлено и 9 удалено
  1. 13 9
      apps/app/src/server/service/attachment.js

+ 13 - 9
apps/app/src/server/service/attachment.js

@@ -44,24 +44,28 @@ class AttachmentService {
     // create an Attachment document and upload file
     let attachment;
     try {
-      const attachedHandlerPromises = this.attachHandlers.map((handler) => {
-        return handler(pageId, file, fileStream);
-      });
-
-      Promise.all(attachedHandlerPromises);
-
       attachment = Attachment.createWithoutSave(pageId, user, file.originalname, file.mimetype, file.size, attachmentType);
       await fileUploadService.uploadAttachment(fileStream, attachment);
       await attachment.save();
+
+      const fileStreamForAttachedHandler = fs.createReadStream(file.path, {
+        flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true,
+      });
+
+      const attachedHandlerPromises = this.attachHandlers.map((handler) => {
+        return handler(pageId, file, fileStreamForAttachedHandler);
+      });
+
+      // Do not await, run in background
+      Promise.all(attachedHandlerPromises).then(() => {
+        onAttached?.(file);
+      });
     }
     catch (err) {
       // delete temporary file
       fs.unlink(file.path, (err) => { if (err) { logger.error('Error while deleting tmp file.') } });
       throw err;
     }
-    finally {
-      onAttached?.(file);
-    }
 
     return attachment;
   }