Repository navigation
Expand file tree
/
Copy pathsetup.js
More file actions
90 lines (80 loc) · 2.45 KB
/
Copy pathsetup.js
File metadata and controls
90 lines (80 loc) · 2.45 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
var r = require('rethinkdb')
var Promise = require('bluebird')
var logger = require('../util/logger')
var tables = require('./tables')
module.exports = function(conn) {
var log = logger.createLogger('db:setup')
function alreadyExistsError(err) {
return err.msg && err.msg.indexOf('already exists') !== -1
}
function noMasterAvailableError(err) {
return err.msg && err.msg.indexOf('No master available') !== -1
}
function createDatabase() {
return r.dbCreate(conn.db).run(conn)
.then(function() {
log.info('Database "%s" created', conn.db)
})
.catch(alreadyExistsError, function() {
log.info('Database "%s" already exists', conn.db)
return Promise.resolve()
})
}
function createTable(table, options) {
var tableOptions = {
primaryKey: options.primaryKey
}
return r.tableCreate(table, tableOptions).run(conn)
.then(function() {
log.info('Table "%s" created', table)
})
.catch(alreadyExistsError, function() {
log.info('Table "%s" already exists', table)
return Promise.resolve()
})
.catch(noMasterAvailableError, function() {
return Promise.delay(1000).then(function() {
return createTable(table, options)
})
})
.then(function() {
if (options.indexes) {
return Promise.all(Object.keys(options.indexes).map(function(index) {
return createIndex(table, index, options.indexes[index])
}))
}
})
}
function createIndex(table, index, options) {
var args = [index]
, rTable = r.table(table)
if (options) {
if (options.indexFunction) {
args.push(options.indexFunction)
}
if (options.options) {
args.push(options.options)
}
}
return rTable.indexCreate.apply(rTable, args).run(conn)
.then(function() {
log.info('Index "%s"."%s" created', table, index)
})
.catch(alreadyExistsError, function() {
log.info('Index "%s"."%s" already exists', table, index)
return Promise.resolve()
})
.catch(noMasterAvailableError, function() {
return Promise.delay(1000).then(function() {
return createIndex(table, index, options)
})
})
}
return createDatabase()
.then(function() {
return Promise.all(Object.keys(tables).map(function(table) {
return createTable(table, tables[table])
}))
})
.return(conn)
}