index.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.GridFSBucket = void 0;
  4. const error_1 = require("../error");
  5. const mongo_types_1 = require("../mongo_types");
  6. const utils_1 = require("../utils");
  7. const write_concern_1 = require("../write_concern");
  8. const download_1 = require("./download");
  9. const upload_1 = require("./upload");
  10. const DEFAULT_GRIDFS_BUCKET_OPTIONS = {
  11. bucketName: 'fs',
  12. chunkSizeBytes: 255 * 1024
  13. };
  14. /**
  15. * Constructor for a streaming GridFS interface
  16. * @public
  17. */
  18. class GridFSBucket extends mongo_types_1.TypedEventEmitter {
  19. constructor(db, options) {
  20. super();
  21. this.setMaxListeners(0);
  22. const privateOptions = {
  23. ...DEFAULT_GRIDFS_BUCKET_OPTIONS,
  24. ...options,
  25. writeConcern: write_concern_1.WriteConcern.fromOptions(options)
  26. };
  27. this.s = {
  28. db,
  29. options: privateOptions,
  30. _chunksCollection: db.collection(privateOptions.bucketName + '.chunks'),
  31. _filesCollection: db.collection(privateOptions.bucketName + '.files'),
  32. checkedIndexes: false,
  33. calledOpenUploadStream: false
  34. };
  35. }
  36. /**
  37. * Returns a writable stream (GridFSBucketWriteStream) for writing
  38. * buffers to GridFS. The stream's 'id' property contains the resulting
  39. * file's id.
  40. *
  41. * @param filename - The value of the 'filename' key in the files doc
  42. * @param options - Optional settings.
  43. */
  44. openUploadStream(filename, options) {
  45. return new upload_1.GridFSBucketWriteStream(this, filename, options);
  46. }
  47. /**
  48. * Returns a writable stream (GridFSBucketWriteStream) for writing
  49. * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting
  50. * file's id.
  51. */
  52. openUploadStreamWithId(id, filename, options) {
  53. return new upload_1.GridFSBucketWriteStream(this, filename, { ...options, id });
  54. }
  55. /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */
  56. openDownloadStream(id, options) {
  57. return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { _id: id }, options);
  58. }
  59. delete(id, callback) {
  60. return (0, utils_1.executeLegacyOperation)((0, utils_1.getTopology)(this.s.db), _delete, [this, id, callback], {
  61. skipSessions: true
  62. });
  63. }
  64. /** Convenience wrapper around find on the files collection */
  65. find(filter, options) {
  66. filter !== null && filter !== void 0 ? filter : (filter = {});
  67. options = options !== null && options !== void 0 ? options : {};
  68. return this.s._filesCollection.find(filter, options);
  69. }
  70. /**
  71. * Returns a readable stream (GridFSBucketReadStream) for streaming the
  72. * file with the given name from GridFS. If there are multiple files with
  73. * the same name, this will stream the most recent file with the given name
  74. * (as determined by the `uploadDate` field). You can set the `revision`
  75. * option to change this behavior.
  76. */
  77. openDownloadStreamByName(filename, options) {
  78. let sort = { uploadDate: -1 };
  79. let skip = undefined;
  80. if (options && options.revision != null) {
  81. if (options.revision >= 0) {
  82. sort = { uploadDate: 1 };
  83. skip = options.revision;
  84. }
  85. else {
  86. skip = -options.revision - 1;
  87. }
  88. }
  89. return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { filename }, { ...options, sort, skip });
  90. }
  91. rename(id, filename, callback) {
  92. return (0, utils_1.executeLegacyOperation)((0, utils_1.getTopology)(this.s.db), _rename, [this, id, filename, callback], {
  93. skipSessions: true
  94. });
  95. }
  96. drop(callback) {
  97. return (0, utils_1.executeLegacyOperation)((0, utils_1.getTopology)(this.s.db), _drop, [this, callback], {
  98. skipSessions: true
  99. });
  100. }
  101. /** Get the Db scoped logger. */
  102. getLogger() {
  103. return this.s.db.s.logger;
  104. }
  105. }
  106. exports.GridFSBucket = GridFSBucket;
  107. /**
  108. * When the first call to openUploadStream is made, the upload stream will
  109. * check to see if it needs to create the proper indexes on the chunks and
  110. * files collections. This event is fired either when 1) it determines that
  111. * no index creation is necessary, 2) when it successfully creates the
  112. * necessary indexes.
  113. * @event
  114. */
  115. GridFSBucket.INDEX = 'index';
  116. function _delete(bucket, id, callback) {
  117. return bucket.s._filesCollection.deleteOne({ _id: id }, (error, res) => {
  118. if (error) {
  119. return callback(error);
  120. }
  121. return bucket.s._chunksCollection.deleteMany({ files_id: id }, error => {
  122. if (error) {
  123. return callback(error);
  124. }
  125. // Delete orphaned chunks before returning FileNotFound
  126. if (!(res === null || res === void 0 ? void 0 : res.deletedCount)) {
  127. // TODO(NODE-3483): Replace with more appropriate error
  128. // Consider creating new error MongoGridFSFileNotFoundError
  129. return callback(new error_1.MongoRuntimeError(`File not found for id ${id}`));
  130. }
  131. return callback();
  132. });
  133. });
  134. }
  135. function _rename(bucket, id, filename, callback) {
  136. const filter = { _id: id };
  137. const update = { $set: { filename } };
  138. return bucket.s._filesCollection.updateOne(filter, update, (error, res) => {
  139. if (error) {
  140. return callback(error);
  141. }
  142. if (!(res === null || res === void 0 ? void 0 : res.matchedCount)) {
  143. return callback(new error_1.MongoRuntimeError(`File with id ${id} not found`));
  144. }
  145. return callback();
  146. });
  147. }
  148. function _drop(bucket, callback) {
  149. return bucket.s._filesCollection.drop((error) => {
  150. if (error) {
  151. return callback(error);
  152. }
  153. return bucket.s._chunksCollection.drop((error) => {
  154. if (error) {
  155. return callback(error);
  156. }
  157. return callback();
  158. });
  159. });
  160. }
  161. //# sourceMappingURL=index.js.map