· 9 years ago · Oct 02, 2016, 11:54 PM
1var express = require('express');
2var app = express();
3var async = require('asyncawait/async');
4var await = require('asyncawait/await');
5
6var config = require(__dirname + "/config.js");
7var r = require('rethinkdb');
8
9
10//
11// Middleware
12//
13
14
15// Middleware that will create a connection to the database
16app.use(createConnection);
17
18// Path routing and other stuff
19app.get('/', (req, res, next) => {
20 // res.send('Hello World!');
21 res.sendFile(__dirname + '/static/index.html');
22 next();
23});
24
25// Middleware to close a connection to the database
26app.use(closeConnection);
27
28
29//
30// Startup code
31//
32
33// Make sure db exists
34
35
36// Make sure db and its tables exist
37// TODO: indexes with tables?
38var dbName = config.rethinkdb.db;
39var TABLES = ['users', 'bloops'];
40r.connect(config.rethinkdb)
41 .then(conn => {
42 // db
43 r.dbList().run(conn)
44 .then(async (dbList => {
45 if (dbList.indexOf(dbName) > -1) {
46 console.log(`Database ${dbName} already exists.`);
47 } else {
48 console.log(`Database ${dbName} not found. Creating.`);
49 await (r.dbCreate(dbName).run(conn));
50 console.log(`Done creating database ${dbName}.`);
51 }
52 }));
53 return conn;
54 }).then(conn => {
55 // tables
56 r.tableList().run(conn)
57 .then(async (tableList => {
58 console.log(`Tables: ${tableList}`);
59 for (tableName of TABLES) {
60 if (tableList.indexOf(tableName) > -1) {
61 console.log(`Table ${tableName} already exists.`);
62 } else {
63 console.log(`Table ${tableName} not found. Creating.`);
64 await (r.tableCreate(tableName).run(conn));
65 console.log(`Done creating table ${tableName}`);
66 }
67 }
68 }));
69 return null;
70 }).then(() => {
71 startExpress();
72 });
73
74
75//
76// Helpers
77//
78
79
80// Opening/closing new DB connection on each request is ok?
81// https://github.com/rethinkdb/rethinkdb/issues/846
82
83/*
84 * Create a RethinkDB connection, and save it in req._rdbConn
85 */
86function createConnection(req, res, next) {
87 r.connect(config.rethinkdb)
88 .then(conn => {
89 req._rdbConn = conn;
90 next();
91 })
92 .error(handleError(res));
93}
94
95/*
96 * Close the RethinkDB connection
97 */
98function closeConnection(req, res, next) {
99 req._rdbConn.close();
100}
101
102/*
103 * Send back a 500 error
104 */
105function handleError(res) {
106 return (error) => {res.send(500, {error: error.message});}
107}
108
109/*
110 * Start express
111 */
112function startExpress() {
113 app.listen(3000, function () {
114 console.log('Example app listening on port 3000!');
115 });
116}