UNPKG

2.34 kBJavaScriptView Raw
1'use strict'
2
3/*!
4 * migrate - Set
5 * Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca>
6 * MIT Licensed
7 */
8
9/**
10 * Module dependencies.
11 */
12
13var EventEmitter = require('events')
14var Migration = require('./migration')
15var migrate = require('./migrate')
16var inherits = require('inherits')
17
18/**
19 * Expose `Set`.
20 */
21
22module.exports = MigrationSet
23
24/**
25 * Initialize a new migration `Set` with the given `path`
26 * which is used to store data between migrations.
27 *
28 * @param {String} path
29 * @api private
30 */
31
32function MigrationSet (store) {
33 this.store = store
34 this.migrations = []
35 this.map = {}
36 this.lastRun = null
37};
38
39/**
40 * Inherit from `EventEmitter.prototype`.
41 */
42
43inherits(MigrationSet, EventEmitter)
44
45/**
46 * Add a migration.
47 *
48 * @param {String} title
49 * @param {Function} up
50 * @param {Function} down
51 * @api public
52 */
53
54MigrationSet.prototype.addMigration = function (title, up, down) {
55 var migration
56 if (!(title instanceof Migration)) {
57 migration = new Migration(title, up, down)
58 } else {
59 migration = title
60 }
61
62 // Only add the migration once, but update
63 if (this.map[migration.title]) {
64 this.map[migration.title].up = migration.up
65 this.map[migration.title].down = migration.down
66 this.map[migration.title].description = migration.description
67 return
68 }
69
70 this.migrations.push(migration)
71 this.map[migration.title] = migration
72}
73
74/**
75 * Save the migration data.
76 *
77 * @api public
78 */
79
80MigrationSet.prototype.save = function (fn) {
81 this.store.save(this, (err) => {
82 if (err) return fn(err)
83 this.emit('save')
84 fn(null)
85 })
86}
87
88/**
89 * Run down migrations and call `fn(err)`.
90 *
91 * @param {Function} fn
92 * @api public
93 */
94
95MigrationSet.prototype.down = function (migrationName, fn) {
96 this.migrate('down', migrationName, fn)
97}
98
99/**
100 * Run up migrations and call `fn(err)`.
101 *
102 * @param {Function} fn
103 * @api public
104 */
105
106MigrationSet.prototype.up = function (migrationName, fn) {
107 this.migrate('up', migrationName, fn)
108}
109
110/**
111 * Migrate in the given `direction`, calling `fn(err)`.
112 *
113 * @param {String} direction
114 * @param {Function} fn
115 * @api public
116 */
117
118MigrationSet.prototype.migrate = function (direction, migrationName, fn) {
119 if (typeof migrationName === 'function') {
120 fn = migrationName
121 migrationName = null
122 }
123 migrate(this, direction, migrationName, fn)
124}