attachment.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import loggerFactory from '~/utils/logger';
  2. import { AttachmentType } from '../interfaces/attachment';
  3. import { Attachment } from '../models';
  4. const fs = require('fs');
  5. const mongoose = require('mongoose');
  6. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  7. const logger = loggerFactory('growi:service:AttachmentService');
  8. /**
  9. * the service class for Attachment and file-uploader
  10. */
  11. class AttachmentService {
  12. constructor(crowi) {
  13. this.crowi = crowi;
  14. }
  15. async createAttachment(file, user, pageId = null, attachmentType) {
  16. const { fileUploadService } = this.crowi;
  17. // check limit
  18. const res = await fileUploadService.checkLimit(file.size);
  19. if (!res.isUploadable) {
  20. throw new Error(res.errorMessage);
  21. }
  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 { fileUploadService } = this.crowi;
  55. const attachment = await Attachment.findById(attachmentId);
  56. await fileUploadService.deleteFile(attachment);
  57. await attachment.remove();
  58. return;
  59. }
  60. async isBrandLogoExist() {
  61. const query = { attachmentType: AttachmentType.BRAND_LOGO };
  62. const count = await Attachment.countDocuments(query);
  63. return count >= 1;
  64. }
  65. }
  66. module.exports = AttachmentService;