This repository has been archived by the owner on Aug 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 106
/
db.js
294 lines (275 loc) · 9.34 KB
/
db.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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// A fork of the [node.js chat app](https://github.com/eiriksm/chat-test-2k)
// by [@orkj](https://twitter.com/orkj) using socket.io, rethinkdb, passport and bcrypt on an express app.
//
// See the [GitHub README](https://github.com/rethinkdb/rethinkdb-example-nodejs-chat/blob/master/README.md)
// for details of the complete stack, installation, and running the app.
var r = require('rethinkdb')
, util = require('util')
, assert = require('assert')
, logdebug = require('debug')('rdb:debug')
, logerror = require('debug')('rdb:error');
// #### Connection details
// RethinkDB database settings. Defaults can be overridden using environment variables.
var dbConfig = {
host: process.env.RDB_HOST || 'localhost',
port: parseInt(process.env.RDB_PORT) || 28015,
db : process.env.RDB_DB || 'chat',
tables: {
'messages': 'id',
'cache': 'cid',
'users': 'id'
}
};
/**
* Connect to RethinkDB instance and perform a basic database setup:
*
* - create the `RDB_DB` database (defaults to `chat`)
* - create tables `messages`, `cache`, `users` in this database
*/
module.exports.setup = function() {
r.connect({host: dbConfig.host, port: dbConfig.port }, function (err, connection) {
assert.ok(err === null, err);
r.dbCreate(dbConfig.db).run(connection, function(err, result) {
if(err) {
logdebug("[DEBUG] RethinkDB database '%s' already exists (%s:%s)\n%s", dbConfig.db, err.name, err.msg, err.message);
}
else {
logdebug("[INFO ] RethinkDB database '%s' created", dbConfig.db);
}
for(var tbl in dbConfig.tables) {
(function (tableName) {
r.db(dbConfig.db).tableCreate(tableName, {primaryKey: dbConfig.tables[tbl]}).run(connection, function(err, result) {
if(err) {
logdebug("[DEBUG] RethinkDB table '%s' already exists (%s:%s)\n%s", tableName, err.name, err.msg, err.message);
}
else {
logdebug("[INFO ] RethinkDB table '%s' created", tableName);
}
});
})(tbl);
}
});
});
};
// #### Filtering results
/**
* Find a user by email using the
* [`filter`](http://www.rethinkdb.com/api/javascript/filter/) function.
* We are using the simple form of `filter` accepting an object as an argument which
* is used to perform the matching (in this case the attribute `mail` must be equal to
* the value provided).
*
* We only need one result back so we use [`limit`](http://www.rethinkdb.com/api/javascript/limit/)
* to return it (if found). The result is collected with [`next`](http://www.rethinkdb.com/api/javascript/next/)
* and passed as an array to the callback function.
*
* @param {String} mail
* the email of the user that we search for
*
* @param {Function} callback
* callback invoked after collecting all the results
*
* @returns {Object} the user if found, `null` otherwise
*/
module.exports.findUserByEmail = function (mail, callback) {
onConnect(function (err, connection) {
logdebug("[INFO ][%s][findUserByEmail] Login {user: %s, pwd: 'you really thought I'd log it?'}", connection['_id'], mail);
r.db(dbConfig.db).table('users').filter({'mail': mail}).limit(1).run(connection, function(err, cursor) {
if(err) {
logerror("[ERROR][%s][findUserByEmail][collect] %s:%s\n%s", connection['_id'], err.name, err.msg, err.message);
callback(err);
}
else {
cursor.next(function (err, row) {
if(err) {
logerror("[ERROR][%s][findUserByEmail][collect] %s:%s\n%s", connection['_id'], err.name, err.msg, err.message);
callback(null, null); // no user, cursor is empty
}
else {
callback(null, row);
}
connection.close();
});
}
});
});
};
/**
* Every user document is assigned a unique id when created. Retrieving
* a document by its id can be done using the
* [`get`](http://www.rethinkdb.com/api/javascript/get/) function.
*
* RethinkDB will use the primary key index to fetch the result.
*
* @param {String} userId
* The ID of the user to be retrieved.
*
* @param {Function} callback
* callback invoked after collecting all the results
*
* @returns {Object} the user if found, `null` otherwise
*/
module.exports.findUserById = function (userId, callback) {
onConnect(function (err, connection) {
r.db(dbConfig['db']).table('users').get(userId).run(connection, function(err, result) {
if(err) {
logerror("[ERROR][%s][findUserById] %s:%s\n%s", connection['_id'], err.name, err.msg, err.message);
callback(null, null);
}
else {
callback(null, result);
}
connection.close();
});
});
};
// #### Retrieving chat messages
/**
* To find the last `max_results` messages ordered by `timestamp`,
* we are using [`table`](http://www.rethinkdb.com/api/javascript/table/) to access
* messages in the table, then we
* [`orderBy`](http://www.rethinkdb.com/api/javascript/order_by/) `timestamp`
* and instruct the server to return only `max_results` using
* [`limit`](http://www.rethinkdb.com/api/javascript/limit/).
*
* These operations are chained together and executed on the database. Results
* are collected with [`toArray`](http://www.rethinkdb.com/api/javascript/toArray)
* and passed as an array to the callback function.
*
*
* @param {Number} max_results
* Maximum number of results to be retrieved from the db
*
* @param {Function} callback
* callback invoked after collecting all the results
*
* @returns {Array} an array of messages
*/
module.exports.findMessages = function (max_results, callback) {
onConnect(function (err, connection) {
r.db(dbConfig['db']).table('messages').orderBy(r.desc('timestamp')).limit(max_results).run(connection, function(err, cursor) {
if(err) {
logerror("[ERROR][%s][findMessages] %s:%s\n%s", connection['_id'], err.name, err.msg, err.message);
callback(null, []);
connection.close();
}
else {
cursor.toArray(function(err, results) {
if(err) {
logerror("[ERROR][%s][findMessages][toArray] %s:%s\n%s", connection['_id'], err.name, err.msg, err.message);
callback(null, []);
}
else {
callback(null, results);
}
connection.close();
});
}
});
});
};
/**
* To save a new chat message using we are using
* [`insert`](http://www.rethinkdb.com/api/javascript/insert/).
*
* An `insert` op returns an object specifying the number
* of successfully created objects and their corresponding IDs:
*
* ```
* {
* "inserted": 1,
* "errors": 0,
* "generated_keys": [
* "b3426201-9992-ab84-4a21-576719746036"
* ]
* }
* ```
*
* @param {Object} msg
* The message to be saved
*
* @param {Function} callback
* callback invoked once after the first result returned
*
* @returns {Boolean} `true` if the user was created, `false` otherwise
*/
module.exports.saveMessage = function (msg, callback) {
onConnect(function (err, connection) {
r.db(dbConfig['db']).table('messages').insert(msg).run(connection, function(err, result) {
if(err) {
logerror("[ERROR][%s][saveMessage] %s:%s\n%s", connection['_id'], err.name, err.msg, err.message);
callback(err);
}
else {
if(result.inserted === 1) {
callback(null, true);
}
else {
callback(null, false);
}
}
connection.close();
});
});
};
/**
* Adding a new user to database using [`insert`](http://www.rethinkdb.com/api/javascript/insert/).
*
* If the document to be saved doesn't have an `id` field, RethinkDB automatically
* generates an unique `id`. This is returned in the result object.
*
* @param {Object} user
* The user JSON object to be saved.
*
* @param {Function} callback
* callback invoked once after the first result returned
*
* @returns {Boolean} `true` if the user was created, `false` otherwise
*/
module.exports.saveUser = function (user, callback) {
onConnect(function (err, connection) {
r.db(dbConfig.db).table('users').insert(user).run(connection, function(err, result) {
if(err) {
logerror("[ERROR][%s][saveUser] %s:%s\n%s", connection['_id'], err.name, err.msg, err.message);
callback(err);
}
else {
if (result.inserted === 1) {
callback(null, true);
}
else {
callback(null, false);
}
}
connection.close();
});
});
};
// #### Helper functions
/**
* A wrapper function for the RethinkDB API `r.connect`
* to keep the configuration details in a single function
* and fail fast in case of a connection error.
*/
function onConnect(callback) {
r.connect({host: dbConfig.host, port: dbConfig.port }, function(err, connection) {
assert.ok(err === null, err);
connection['_id'] = Math.floor(Math.random()*10001);
callback(err, connection);
});
}
// #### Connection management
//
// This application uses a new connection for each query needed to serve
// a user request. In case generating the response would require multiple
// queries, the same connection should be used for all queries.
//
// Example:
//
// onConnect(function (err, connection)) {
// if(err) { return callback(err); }
//
// query1.run(connection, callback);
// query2.run(connection, callback);
// }
//