attachment.js 2.1 KB

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