attachment.js 2.2 KB

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