forked from kriasoft/graphql-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
64 lines (57 loc) · 1.74 KB
/
db.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
/**
* Node.js API Starter Kit (https://reactstarter.com/nodejs)
*
* Copyright © 2016-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
const fs = require('fs');
const knex = require('knex');
const task = require('./task');
// The list of available commands, e.g. node scripts/db.js migrate:undo
const commands = ['version', 'migrate', 'migrate:undo', 'migration', 'seed'];
const command = process.argv[2];
const config = {
client: 'pg',
connection: process.env.DATABASE_URL,
migrations: {
tableName: 'migrations',
},
};
// The template for database migration files (see templates/*.js)
const version = new Date().toISOString().substr(0, 16).replace(/\D/g, '');
const template = `module.exports.up = async (db) => {\n \n};\n
module.exports.down = async (db) => {\n \n};\n
module.exports.configuration = { transaction: true };\n`;
module.exports = task('db', async () => {
let db;
if (!commands.includes(command)) {
throw new Error(`Unknown command: ${command}`);
}
try {
switch (command) {
case 'version':
db = knex(config);
await db.migrate.currentVersion(config).then(console.log);
break;
case 'migration':
fs.writeFileSync(`migrations/${version}_${process.argv[3] || 'new'}.js`, template, 'utf8');
break;
case 'migrate:undo':
db = knex(config);
await db.migrate.rollback(config);
break;
case 'seed':
console.error('Not yet implemented.');
break;
default:
db = knex(config);
await db.migrate.latest(config);
}
} finally {
if (db) {
await db.destroy();
}
}
});