forked from kriasoft/graphql-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
71 lines (64 loc) · 1.72 KB
/
db.js
File metadata and controls
71 lines (64 loc) · 1.72 KB
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
#!/usr/bin/env node
/**
* Copyright © 2016-present Kriasoft.
*
* 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 tools/db.js rollback
const commands = ['version', 'migrate', 'rollback', '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 'rollback':
db = knex(config);
await db.migrate.rollback(config);
break;
case 'seed':
db = knex(config);
await db.seed.run(config);
break;
default:
db = knex(config);
await db.migrate.latest(config);
}
} finally {
if (db) {
await db.destroy();
}
}
});