소스 검색

refactor: enhance type safety in AttachmentService and add error handling for missing attachments

Yuki Takei 4 달 전
부모
커밋
eea328f035
1개의 변경된 파일16개의 추가작업 그리고 8개의 파일을 삭제
  1. 16 8
      apps/app/src/server/service/attachment.ts

+ 16 - 8
apps/app/src/server/service/attachment.ts

@@ -1,5 +1,8 @@
+import type { IAttachment } from '@growi/core/dist/interfaces';
+
 import loggerFactory from '~/utils/logger';
 import loggerFactory from '~/utils/logger';
 
 
+import type Crowi from '../crowi';
 import { AttachmentType } from '../interfaces/attachment';
 import { AttachmentType } from '../interfaces/attachment';
 import { Attachment } from '../models/attachment';
 import { Attachment } from '../models/attachment';
 
 
@@ -16,22 +19,23 @@ const createReadStream = (filePath) => {
   });
   });
 };
 };
 
 
+type AttachHandler = (pageId: string | null, attachment: IAttachment, file: Express.Multer.File) => Promise<void>;
+
+type DetachHandler = (attachmentId: string) => Promise<void>;
+
+
 /**
 /**
  * the service class for Attachment and file-uploader
  * the service class for Attachment and file-uploader
  */
  */
 class AttachmentService {
 class AttachmentService {
 
 
-  /** @type {Array<(pageId: string, attachment: Attachment, file: Express.Multer.File) => Promise<void>>} */
-  attachHandlers = [];
+  attachHandlers: AttachHandler[] = [];
 
 
-  /** @type {Array<(attachmentId: string) => Promise<void>>} */
-  detachHandlers = [];
+  detachHandlers: DetachHandler[] = [];
 
 
-  /** @type {import('~/server/crowi').default} Crowi instance */
-  crowi;
+  crowi: Crowi;
 
 
-  /** @param {import('~/server/crowi').default} crowi Crowi instance */
-  constructor(crowi) {
+  constructor(crowi: Crowi) {
     this.crowi = crowi;
     this.crowi = crowi;
   }
   }
 
 
@@ -101,6 +105,10 @@ class AttachmentService {
     const { fileUploadService } = this.crowi;
     const { fileUploadService } = this.crowi;
     const attachment = await Attachment.findById(attachmentId);
     const attachment = await Attachment.findById(attachmentId);
 
 
+    if (attachment == null) {
+      throw new Error(`Attachment not found: ${attachmentId}`);
+    }
+
     await fileUploadService.deleteFile(attachment);
     await fileUploadService.deleteFile(attachment);
     await attachment.remove();
     await attachment.remove();