attachment.js 2.5 KB

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