Skip to content
This repository was archived by the owner on Apr 20, 2021. It is now read-only.

Commit 53d7770

Browse files
author
Ricardo Malta
committed
Documentation
Get some comments better Coding style in some documents
1 parent b0eb26b commit 53d7770

File tree

8 files changed

+70
-56
lines changed

8 files changed

+70
-56
lines changed

bin/index.js

+9-24
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,35 @@
11
#!/usr/bin/env node
22

3-
/**
4-
* Module dependencies.
5-
*/
3+
// Module dependencies.
64
const app = require('../lib/app');
75
const debug = require('debug')('node-rethinkdb-echo:server');
86
const http = require('http');
97
const config = require('config');
108
const log = require('../lib/logger').log('www');
119
const socket = require('../lib/socket');
1210

13-
/**
14-
* Get port from environment and store in Express.
15-
*/
11+
// Get port from environment and store in Express.
1612
const port = normalizePort(process.env.PORT || config.get('web.port'));
1713
app.set('port', port);
1814

19-
/**
20-
* Create HTTP server.
21-
*/
15+
// Create HTTP server.
2216
const server = http.createServer(app);
2317

24-
/**
25-
* Create the Socket IO server
26-
*/
18+
// Create the Socket IO server
2719
socket(server, (err, res) => {
2820
if (err) {
2921
log.error(err);
3022
} else {
3123
log.info('Socket.io initialized successefully!');
3224
}
3325
});
34-
/**
35-
* Listen on provided port, on all network interfaces.
36-
*/
26+
27+
// Listen on provided port, on all network interfaces.
3728
server.listen(port, '0.0.0.0');
3829
server.on('error', onError);
3930
server.on('listening', onListening);
4031

41-
/**
42-
* Normalize a port into a number, string, or false.
43-
*/
32+
// Normalize a port into a number, string, or false.
4433
function normalizePort (val) {
4534
const port = parseInt(val, 10);
4635

@@ -57,9 +46,7 @@ function normalizePort (val) {
5746
return false;
5847
}
5948

60-
/**
61-
* Event listener for HTTP server "error" event.
62-
*/
49+
// Event listener for HTTP server "error" event.
6350
function onError (error) {
6451
if (error.syscall !== 'listen') {
6552
throw error;
@@ -84,9 +71,7 @@ function onError (error) {
8471
}
8572
}
8673

87-
/**
88-
* Event listener for HTTP server "listening" event.
89-
*/
74+
// Event listener for HTTP server "listening" event.
9075
function onListening () {
9176
const addr = server.address();
9277
const bind = typeof addr === 'string'

config/nginx/site.conf

+23-24
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,33 @@
11
upstream service {
2-
server 127.0.0.1:9700;
2+
server 127.0.0.1:9700;
33
}
44

55
server {
6-
listen 443 ssl default_server;
7-
server_name api.earfy.net;
6+
listen 443 ssl default_server;
7+
server_name api.earfy.net;
88

9-
# ssl_certificate /etc/letsencrypt/live/MY_HOST_DOMAIN/fullchain.pem;
10-
# ssl_certificate_key /etc/letsencrypt/live/MY_HOST_DOMAIN/privkey.pem;
9+
# ssl_certificate /etc/letsencrypt/live/MY_HOST_DOMAIN/fullchain.pem;
10+
# ssl_certificate_key /etc/letsencrypt/live/MY_HOST_DOMAIN/privkey.pem;
1111

12-
location / {
12+
location / {
13+
auth_basic "Restricted Content";
14+
auth_basic_user_file /etc/nginx/.htpasswd;
1315

14-
auth_basic "Restricted Content";
15-
auth_basic_user_file /etc/nginx/.htpasswd;
16+
proxy_set_header X-Real-IP $remote_addr;
17+
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
18+
proxy_set_header Host $host;
19+
proxy_set_header X-NginX-Proxy true;
1620

17-
proxy_set_header X-Real-IP $remote_addr;
18-
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
19-
proxy_set_header Host $host;
20-
proxy_set_header X-NginX-Proxy true;
21+
proxy_pass http://service;
22+
proxy_redirect off;
23+
}
2124

22-
proxy_pass http://service;
23-
proxy_redirect off;
24-
}
25-
26-
location /socket.io {
27-
proxy_set_header Upgrade $http_upgrade;
28-
proxy_set_header Connection "upgrade";
29-
proxy_http_version 1.1;
30-
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
31-
proxy_set_header Host $host;
32-
proxy_pass http://service;
33-
}
25+
location /socket.io {
26+
proxy_set_header Upgrade $http_upgrade;
27+
proxy_set_header Connection "upgrade";
28+
proxy_http_version 1.1;
29+
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
30+
proxy_set_header Host $host;
31+
proxy_pass http://service;
32+
}
3433
}

lib/broker.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,16 @@
33
const log = require('./logger').log('broker');
44
const EventEmitter = require('events').EventEmitter;
55

6+
// create and extends from the EventEmitter
67
class Broker extends EventEmitter {
78

9+
// ensure format and send messages to the listeners.
810
send (event = 'unknown', room = 'public', message) {
911
if (!message) {
1012
log.error('Nothing to send, aborting the event emit!');
1113
return;
1214
}
13-
15+
// just to ensure that the event looper is healthy.
1416
setImmediate(() => {
1517
this.emit(event, { room, message });
1618
});

lib/controllers/messages.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,14 @@ const models = require('../models');
99
router.post('/', function (req, res, next) {
1010
var objects = req.body || null;
1111

12+
// no objects in the http body, then let the user now that he is doing something wrong!
1213
if (objects == null) {
1314
res.status(400);
1415
return res.json({error: 'Invalid POST format.'});
1516
}
1617

1718
var items = typeof objects === 'object' && objects instanceof Array ? objects : [objects];
18-
19+
// Before save the message items in the DB, lets do some checks to each one.
1920
async.each(items,
2021
function (item, next) {
2122
// enforce author to be a string without spaces
@@ -26,6 +27,7 @@ router.post('/', function (req, res, next) {
2627
if (typeof item.Room === 'string' && !item.Room.match(/^\w+$/)) {
2728
return next('Invalid room name!');
2829
}
30+
// send the message to the model, in order to save it in the DB.
2931
models.messages.insert(item.Author, item.Room, item.Text, next);
3032
},
3133
function (err) {

lib/db.js

+2
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@ const log = require('./logger').log('db');
44
const config = require('config');
55
const thinky = require('thinky')(config.get('rethinkdb'));
66

7+
// expose the Thinky instance.
78
exports.thinky = thinky;
89

10+
// use close to dispose the database connections properly (aka: gracefully shutdown).
911
exports.close = (callback) => {
1012
thinky.r.getPoolMaster().on('log', log.info);
1113
thinky.r.getPoolMaster().drain();

lib/logger.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@ const winston = require('winston');
44
const expressWinston = require('express-winston');
55
const loggers = {};
66

7+
// an abstration to wiston logger.
78
exports.log = (name) => {
89
if (loggers[name]) {
910
return loggers[name];
1011
}
11-
1212
loggers[name] = new winston.Logger({
1313
transports: [
1414
new winston.transports.Console({
@@ -25,6 +25,7 @@ exports.log = (name) => {
2525
return loggers[name];
2626
};
2727

28+
// to HTTP
2829
exports.http = expressWinston.logger({
2930
transports: [
3031
new winston.transports.Console({

lib/models/messages.js

+23-4
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,30 @@ const r = thinky.r;
88

99
// Define the Message model
1010
const Message = thinky.createModel('messages', {
11+
// non optional string field with maximum 1024 caracthers.
1112
Text: type.string().max(1024).required(),
1213
Room: type.string().default('public'),
1314
CreateDate: type.date().default(r.now())
1415
});
1516

1617
// Ensure the secondary indexes
18+
// optional, to get all messages form a user, its nice to have the proper index.
1719
Message.ensureIndex('Author');
20+
// mandatory to list the messages of a room.
1821
Message.ensureIndex('Room');
22+
// mandatory to order the results chronologically.
1923
Message.ensureIndex('CreateDate');
2024

2125
// Message change feed registration and handling
26+
// Here is where the magic happens, every change in the message colletion will end up here.
27+
// this implementation is based on the Thinky syntax: https://thinky.io/documentation/feeds/
2228
Message.changes().then((changes) => {
29+
// just in case...
2330
if (changes == null) {
2431
return;
2532
}
2633

34+
// the changes argument cames in a list of changes.
2735
return changes.each((err, message) => {
2836
if (err) {
2937
log.error(err);
@@ -36,38 +44,49 @@ Message.changes().then((changes) => {
3644
}
3745

3846
log.info(message);
47+
// send the message throught the intra-process message broker
3948
broker.send('message', message.Room, message);
4049
});
4150
}).error((error) => {
51+
// if there is an error at this stage, it doesn't manner, just log it.
4252
log.error(error);
4353
});
4454

55+
// List messages by room.
4556
exports.list = (room = 'public', callback) => {
57+
// implememed using the Thinky model and the standard ReQL syntax to:
58+
// Order, spefic room, limit to the last 50 (first step to pagination)
4659
Message
60+
// Order by CreateDate descendently.
4761
.orderBy({index: r.desc('CreateDate')})
62+
// Filter the results by the Room index
4863
.filter(r.row('Room').eq(room))
64+
// Slice for the first 50 results. (use slice and skip to pagination)
4965
.slice(0, 50)
66+
// ask for execute
5067
.run()
68+
// after the promise is resolved
5169
.then((objects) => {
5270
return callback(null, objects);
5371
})
72+
// if its rejected!
5473
.error((err) => {
5574
log.error(err);
5675
return callback(err);
5776
});
5877
};
5978

60-
/*
61-
TODO:
62-
Check the room authorization
63-
*/
79+
// insert new messages.
6480
exports.insert = (user = 'Blaster', room = 'public', text, callback) => {
6581
// with the Message model, save a new message
6682
Message
83+
// I just use a list, because I can. It could save a single object or a list of objects
6784
.save([
6885
{ Author: user, Room: room, Text: text }
86+
// after the promise is resolved
6987
]).then((result) => {
7088
return callback(null, result);
89+
// if its rejected!
7190
}).error((err) => {
7291
log.error(err);
7392
return callback(err);

lib/socket.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const log = require('./logger').log('socket.io');
55
const models = require('./models');
66
const broker = require('./broker');
77

8+
// this is a business level abstration of the sockets.
89
module.exports = (server, callback) => {
910
let io;
1011
try {
@@ -14,7 +15,9 @@ module.exports = (server, callback) => {
1415
log.error(e);
1516
return callback(e);
1617
}
17-
18+
// everytime someone connects:
19+
// 1. join the public room (private rooms perfectly possible).
20+
// 2. receive the last few messages in the public channel.
1821
io.on('connection', (socket) => {
1922
socket.join('public');
2023
log.info(socket.id, 'connected');
@@ -30,6 +33,7 @@ module.exports = (server, callback) => {
3033
});
3134
});
3235

36+
// listen to every message send.
3337
broker.on('message', (data) => {
3438
log.info(`message to ${data.room} channel: ${data.message.Text}`);
3539
io.to(data.room).emit('messages', data.message);

0 commit comments

Comments
 (0)