forked from GordyD/3ree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbSetup.js
61 lines (52 loc) · 1.45 KB
/
dbSetup.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
import r from 'rethinkdb';
import config from 'config';
const rethinkdb = config.get('rethinkdb');
let DATABASE = rethinkdb.db || 'pulse';
let TABLES = ['pulses'];
r.connect(rethinkdb)
.then(conn => {
console.log(' [-] Database Setup');
return createDbIfNotExists(conn)
.then(() => Promise.all(TABLES.map((table) => createTableIfNotExists(conn, table))))
.then(() => closeConnection(conn));
});
function createDbIfNotExists(conn){
return getDbList(conn)
.then((list) => {
if(list.indexOf(DATABASE) === -1) {
return createDatabase(conn);
} else {
console.log(' [!] Database already exists:', DATABASE);
return Promise.resolve(true);
}
});
}
function createTableIfNotExists(conn, table) {
return getTableList(conn)
.then((list) => {
if(list.indexOf(table) === -1) {
return createTable(conn, table);
} else {
console.log(' [!] Table already exists:', table);
return Promise.resolve(true);
}
});
}
function getDbList(conn) {
return r.dbList().run(conn);
}
function getTableList(conn) {
return r.db(DATABASE).tableList().run(conn);
}
function createDatabase(conn) {
console.log(' [-] Create Database:', DATABASE);
return r.dbCreate(DATABASE).run(conn);
}
function createTable(conn, table) {
console.log(' [-] Create Table:', table);
return r.db(DATABASE).tableCreate(table).run(conn);
}
function closeConnection(conn) {
console.log(' [x] Close connection!');
return conn.close();
}