-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
98 lines (85 loc) · 2.44 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"use strict";
const Migration = require("./migration");
const logMigrationNames = (log, migrations) =>
migrations
.map(migration => migration.file)
.forEach(migration => log(migration));
class ServerlessUmzugMigrations {
constructor(serverless, options) {
this.serverless = serverless;
this.log = message =>
serverless.cli.log.bind(serverless.cli)(`Migrations - ${message}`);
this.options = options;
this.commands = {
migrate: {
usage: "Runs database migrations",
commands: {
up: {
usage: "Runs forward migrations",
lifecycleEvents: ["migrate"]
},
down: {
usage: "Rolls back migration",
lifecycleEvents: ["rollback"]
}
}
}
};
this.hooks = {
"after:deploy:deploy": this.afterDeploy.bind(this),
"migrate:up:migrate": this.migrate.bind(this),
"migrate:down:rollback": this.rollback.bind(this)
};
}
afterDeploy() {
if (this.options.function) {
this.log(`Calling migration function: ${this.options.function}`);
this.serverless.pluginManager.invoke(["invoke"]);
} else {
this.log("No migration function defined");
this.log("Specify a function name using the --function / -f option.");
}
}
migrate() {
const migration = new Migration(this.getDatabaseConnectionString());
return migration
.up()
.then(executedMigrations => {
logMigrationNames(
name => this.log(`Applied migration ${name}`),
executedMigrations
);
migration.close();
})
.catch(err => {
this.log("Failed to execute migrations.");
this.log(err);
migration.close();
});
}
rollback() {
const migration = new Migration(this.getDatabaseConnectionString());
return migration
.down()
.then(rolledbackMigrations => {
logMigrationNames(
name => this.log(`Rolled back migration ${name}`),
rolledbackMigrations
);
migration.close();
})
.catch(err => {
this.log("Failed to roll back migrations.");
this.log(err);
migration.close();
});
}
getDatabaseConnectionString() {
if (!process.env.DATABASE_URL) {
this.log("DATABASE_URL environment variable required");
process.exit(1);
}
return process.env.DATABASE_URL;
}
}
module.exports = ServerlessUmzugMigrations;