MongoDBStorage.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _Storage = _interopRequireDefault(require("./Storage"));
  7. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8. /**
  9. * @class MongoDBStorage
  10. */
  11. class MongoDBStorage extends _Storage.default {
  12. /**
  13. * Constructs MongoDB collection storage.
  14. *
  15. * @param {Object} [options]
  16. * Required either connection and collectionName OR collection
  17. * @param {String} [options.connection] - a connection to target database established with MongoDB Driver
  18. * @param {String} [options.collectionName] - name of migration collection in MongoDB
  19. * @param {String} [options.collection] - reference to a MongoDB Driver collection
  20. */
  21. constructor({
  22. connection,
  23. collectionName,
  24. collection
  25. }) {
  26. super();
  27. this.connection = connection;
  28. this.collection = collection;
  29. this.collectionName = collectionName || 'migrations';
  30. if (!this.connection && !this.collection) {
  31. throw new Error('MongoDB Connection or Collection required');
  32. }
  33. if (!this.collection) {
  34. this.collection = this.connection.collection(this.collectionName);
  35. }
  36. }
  37. /**
  38. * Logs migration to be considered as executed.
  39. *
  40. * @param {String} migrationName - Name of the migration to be logged.
  41. * @returns {Promise}
  42. */
  43. logMigration(migrationName) {
  44. return this.collection.insertOne({
  45. migrationName
  46. });
  47. }
  48. /**
  49. * Unlogs migration to be considered as pending.
  50. *
  51. * @param {String} migrationName - Name of the migration to be unlogged.
  52. * @returns {Promise}
  53. */
  54. unlogMigration(migrationName) {
  55. return this.collection.removeOne({
  56. migrationName
  57. });
  58. }
  59. /**
  60. * Gets list of executed migrations.
  61. *
  62. * @returns {Promise.<String[]>}
  63. */
  64. executed() {
  65. return this.collection.find({}).sort({
  66. migrationName: 1
  67. }).toArray().then(records => records.map(r => r.migrationName));
  68. }
  69. }
  70. exports.default = MongoDBStorage;