gridfs.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. const debug = require('debug')('growi:service:fileUploaderGridfs');
  2. const logger = require('@alias/logger')('growi:service:fileUploaderGridfs');
  3. const mongoose = require('mongoose');
  4. const util = require('util');
  5. module.exports = function(crowi) {
  6. 'use strict';
  7. const lib = {};
  8. // instantiate mongoose-gridfs
  9. const gridfs = require('mongoose-gridfs')({
  10. collection: 'attachmentFiles',
  11. model: 'AttachmentFile',
  12. mongooseConnection: mongoose.connection
  13. });
  14. // obtain a model
  15. const AttachmentFile = gridfs.model;
  16. const Chunks = mongoose.model('Chunks', gridfs.schema, 'attachmentFiles.chunks');
  17. // create promisified method
  18. AttachmentFile.promisifiedWrite = util.promisify(AttachmentFile.write).bind(AttachmentFile);
  19. // delete a file
  20. lib.deleteFile = async function(fileId, filePath) {
  21. debug('File deletion: ' + fileId);
  22. const file = await getFile(filePath);
  23. const id = file.id;
  24. AttachmentFile.unlinkById(id, function(error, unlinkedAttachment) {
  25. if (error) {
  26. throw new Error(error);
  27. }
  28. });
  29. // clearCache(fileId);
  30. };
  31. /**
  32. * get size of data uploaded files using (Promise wrapper)
  33. */
  34. const getCollectionSize = () => {
  35. return new Promise((resolve, reject) => {
  36. Chunks.collection.stats((err, data) => {
  37. if (err) {
  38. reject(err);
  39. }
  40. resolve(data.size);
  41. });
  42. });
  43. };
  44. /**
  45. * chech storage for fileUpload reaches MONGO_GRIDFS_TOTAL_LIMIT (for gridfs)
  46. */
  47. lib.checkCapacity = async(uploadFileSize) => {
  48. // skip checking if env var is undefined
  49. if (process.env.MONGO_GRIDFS_TOTAL_LIMIT == null) {
  50. return true;
  51. }
  52. const usingFilesSize = await getCollectionSize();
  53. return (+process.env.MONGO_GRIDFS_TOTAL_LIMIT > usingFilesSize + +uploadFileSize);
  54. };
  55. lib.uploadFile = async function(fileStream, fileName, contentType) {
  56. logger.debug(`File uploading: fileName=${fileName}`);
  57. AttachmentFile.promisifiedWrite({ filename: fileName, contentType }, fileStream);
  58. };
  59. /**
  60. * Find data substance
  61. *
  62. * @param {Attachment} attachment
  63. * @return {stream.Readable} readable stream
  64. */
  65. lib.findDeliveryFile = async function(attachment) {
  66. const attachmentFile = await AttachmentFile.findOne({ filename: attachment.fileName });
  67. if (attachmentFile == null) {
  68. throw new Error(`Any AttachmentFile that relate to the Attachment (${attachment._id.toString()}) does not exist in GridFS`);
  69. }
  70. // return stream.Readable
  71. return AttachmentFile.readById(attachmentFile._id);
  72. };
  73. return lib;
  74. };