attachment.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. fileUploadService.deleteFiles(attachments);
  42. attachments.forEach((attachment) => {
  43. unorderAttachmentsBulkOp.find({ _id: attachment._id }).remove();
  44. });
  45. await unorderAttachmentsBulkOp.execute();
  46. }
  47. return;
  48. }
  49. async removeAttachment(attachmentId) {
  50. const Attachment = this.crowi.model('Attachment');
  51. const { fileUploadService } = this.crowi;
  52. const attachment = await Attachment.findById(attachmentId);
  53. await fileUploadService.deleteFile(attachment);
  54. await attachment.remove();
  55. return;
  56. }
  57. }
  58. module.exports = AttachmentService;