-
-
Save v9n/967e9028f69d72060166517f5a3fabc0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import r from 'rethinkdb'; | |
import config from '../config'; | |
const createDatabase = (conn, name) => | |
r.dbList().contains(name) | |
.do(containsDb => | |
r.branch( | |
containsDb, | |
{ created: 0 }, | |
r.dbCreate(name) | |
) | |
) | |
.run(conn) | |
.error(err => { | |
console.log(`Could not create ${name} DB`); | |
console.log(err.message || 'Something bad happened'); | |
process.exit(1); | |
}); | |
const createTable = (conn, name) => | |
r.tableList().contains(name) | |
.do(containsTable => | |
r.branch( | |
containsTable, | |
{ created: 0 }, | |
r.tableCreate(name) | |
) | |
) | |
.run(conn) | |
.error(err => { | |
console.log(`Could not create ${name} table`); | |
console.log(err.message || 'Somthing bad happened'); | |
process.exit(1); | |
}); | |
const createIndex = (conn, tableName, indexName) => | |
r.table(tableName).indexList().contains(indexName) | |
.do(containsIndex => | |
r.branch( | |
containsIndex, | |
{ created: 0 }, | |
r.table(tableName).indexCreate(indexName) | |
) | |
) | |
.run(conn) | |
.error(err => { | |
console.log(`Could not crate index ${indexName} in ${tableName}`); | |
console.log(err.message || 'Something bad happened'); | |
process.exit(1); | |
}); | |
const waitForIndex = (conn, tableName, indexName) => | |
r.table(tableName).indexWait(indexName) | |
.run(conn) | |
.error(err => { | |
console.log('Something bad happened while waiting for index created'); | |
console.log(err.message || 'Something bad happened'); | |
process.exit(1); | |
}); | |
export const setup = startApp => { | |
r.connect(config.rethinkdb) | |
.then(conn => { | |
createDatabase(conn, 'test'); | |
return conn; | |
}) | |
.then(conn => { | |
return Promise.all([ | |
createTable(conn, 'todos'), | |
createTable(conn, 'days'), | |
]).then((result) => conn, (reason) => conn) | |
}) | |
.then(conn => { | |
return Promise.all([ | |
createIndex(conn, 'todos', 'createdAt'), | |
createIndex(conn, 'days', 'date'), | |
]).then(() => conn, () => conn) | |
}) | |
.then(conn => { | |
return Promise.all([ | |
waitForIndex(conn, 'todos', 'createdAt'), | |
waitForIndex(conn, 'days', 'date'), | |
]) | |
} | |
) | |
.then(() => { | |
console.log('DB and tables are available, starting Koa ...'); | |
startApp(); | |
}) | |
.error(err => { | |
console.log('Could not open a connection to initiailize the database'); | |
console.log(err.message || 'Something bad happened'); | |
process.exit(1); | |
}); | |
}; | |
setup() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment