attachment.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const logger = require('@alias/logger')('growi:service:AttachmentService'); // eslint-disable-line no-unused-vars
  2. const fs = require('fs');
  3. /**
  4. * the service class for Attachment and file-uploader
  5. */
  6. class AttachmentService {
  7. constructor(crowi) {
  8. this.crowi = crowi;
  9. }
  10. async createAttachment(file, user, pageId = null) {
  11. const { fileUploadService } = this.crowi;
  12. // check limit
  13. const res = await fileUploadService.checkLimit(file.size);
  14. if (!res.isUploadable) {
  15. throw new Error(res.errorMessage);
  16. }
  17. const Attachment = this.crowi.model('Attachment');
  18. const fileStream = fs.createReadStream(file.path, {
  19. flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true,
  20. });
  21. // create an Attachment document and upload file
  22. let attachment;
  23. try {
  24. attachment = Attachment.createWithoutSave(pageId, user, fileStream, file.originalname, file.mimetype, file.size);
  25. await fileUploadService.uploadFile(fileStream, attachment);
  26. await attachment.save();
  27. }
  28. catch (err) {
  29. // delete temporary file
  30. fs.unlink(file.path, (err) => { if (err) { logger.error('Error while deleting tmp file.') } });
  31. throw err;
  32. }
  33. return attachment;
  34. }
  35. async removeAttachment(attachments) {
  36. const { fileUploadService } = this.crowi;
  37. return attachments.forEach((attachment) => {
  38. fileUploadService.deleteFile(attachment);
  39. attachment.remove();
  40. });
  41. }
  42. }
  43. module.exports = AttachmentService;