Skip to content
This repository was archived by the owner on Nov 22, 2018. It is now read-only.

Commit afdd2af

Browse files
author
Andrew Hobden
committed
Comments
1 parent 0494fe5 commit afdd2af

File tree

2 files changed

+51
-33
lines changed

2 files changed

+51
-33
lines changed

.jshintrc

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"latedef": "nofunc",
3+
"node": true
4+
}

init.js

+47-33
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,14 @@ var async = require('async'),
44
_ = require('lodash'),
55
logger = require('./lib/logger');
66

7+
/**
8+
* Callback levels:
9+
* - next: Top scope.
10+
* - callback: Second scope.
11+
* - cb: Third scope.
12+
* ... After that, you're on your own.
13+
*/
14+
715
async.auto({
816
environment: environment,
917
validators: validators,
@@ -15,7 +23,7 @@ async.auto({
1523
routes: [ 'validators', 'models', 'httpd', routes ]
1624
}, complete);
1725

18-
function environment(callback) {
26+
function environment(next) {
1927
if (!process.env.SECRET) {
2028
logger.warn('No $SECRET present. Generating a temporary random value.');
2129
process.env.SECRET = require('crypto').randomBytes(256);
@@ -32,7 +40,7 @@ function environment(callback) {
3240
logger.warn('No PROVIDER_URL present. Defaulting to `https://localhost:8080`.');
3341
process.env.PROVIDER_URL = 'https://localhost:8080';
3442
}
35-
return callback(null);
43+
return next(null);
3644
}
3745

3846
/**
@@ -43,8 +51,8 @@ function certificate(next) {
4351
var fs = require('fs');
4452
// Get the certificates.
4553
async.auto({
46-
key: function (next) { fs.readFile('cert/server.key', 'utf8', next); },
47-
cert: function (next) { fs.readFile('cert/server.crt', 'utf8', next); }
54+
key: function (callback) { fs.readFile('cert/server.key', 'utf8', callback); },
55+
cert: function (callback) { fs.readFile('cert/server.crt', 'utf8', callback); }
4856
}, function (error, results) {
4957
if (error) { generateCertificate(error, results, next); }
5058
else { return next(error, results); }
@@ -56,63 +64,62 @@ function certificate(next) {
5664
* @param {Object|null} results - Passed to `next`.
5765
* @param {Function} next - The callback. Is passed `error` (if not a certificate error) and `results`.
5866
*/
59-
function generateCertificate(error, results, next) {
67+
function generateCertificate(error, results, callback) {
6068
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; // Tell Node it's okay.
6169
if (error && error.code === 'ENOENT') {
6270
logger.warn('No certificates present in `cert/{server.key, server.crt}`. Generating a temporary certificate.');
6371
require('pem').createCertificate({ days: 1, selfSigned: true }, function formatKey(error, keys) {
6472
if (error) { return next(error, null); }
65-
return next(null, {key: keys.serviceKey, cert: keys.certificate });
73+
return callback(null, {key: keys.serviceKey, cert: keys.certificate });
6674
});
6775
} else {
68-
return next(error, results);
76+
return callback(error, results);
6977
}
7078
}
7179
}
7280

73-
function middleware(callback, data) {
81+
function middleware(next, data) {
7482
function providerRequest(req, path, callback) {
7583
require('request').get({ url: process.env.PROVIDER_URL + path, json: true }, function (error, request, body) {
7684
callback(error, request);
7785
});
7886
// Callback should be (error, request)
7987
}
80-
function populateVisualizationList(req, res, next) {
88+
function populateVisualizationList(req, res, callback) {
8189
// TODO: Cache this per user.
8290
providerRequest(req, '/api', function validation(error, request) {
8391
if (error) { return next(error); }
8492
var validated = data.validators.list(request.body);
8593
console.log(validated.valid);
8694
if (validated.valid === true) {
8795
req.visualizations = request.body.visualizations;
88-
next();
96+
callback();
8997
} else {
90-
next(new Error(JSON.stringify(validated, 2)));
98+
callback(new Error(JSON.stringify(validated, 2)));
9199
}
92100
});
93101
}
94-
function populateVisualization(req, res, next) {
102+
function populateVisualization(req, res, callback) {
95103
if (!req.params.title) { return res.redirect('/'); }
96104
providerRequest(req, '/api/' + req.params.title, function validation(error, request) {
97105
if (error) { return next(error); }
98106
var validated = data.validators.item(request.body);
99-
console.log(validated.valid);
100107
if (validated.valid === true) {
101108
req.visualization = request.body;
102-
next();
109+
callback();
103110
} else {
104-
next(new Error(JSON.stringify(validated, 2)));
111+
callback(new Error(JSON.stringify(validated, 2)));
105112
}
106113
});
107114
}
108-
return callback(null, {
115+
return next(null, {
109116
populateVisualizationList: populateVisualizationList,
110117
populateVisualization: populateVisualization,
111118
providerRequest: providerRequest
112119
});
113120
}
114121

115-
function httpd(callback, data) {
122+
function httpd(next, data) {
116123
var server = require('express')();
117124
// Set the server engine.
118125
server.set('view engine', 'hbs');
@@ -141,34 +148,39 @@ function httpd(callback, data) {
141148
// server.use(require('csurf')());
142149
// Compresses responses.
143150
server.use(require('compression')());
144-
return callback(null, server);
151+
return next(null, server);
145152
}
146153

147-
function database(callback, data) {
154+
/**
155+
* This task sets up MongoDB and will not invoke next until it has either connected or errored.
156+
*/
157+
function database(next, data) {
148158
var connection = require('mongoose').connect(process.env.MONGO_URI).connection;
159+
// This is an event handler.
160+
// The mongoose library emits events (open or error) when it connects (or fails to)
149161
connection.on('open', function () {
150162
logger.log('Connected to database on ' + process.env.MONGO_URI);
151-
return callback(null);
163+
return next(null);
152164
});
153165
connection.on('error', function (error) {
154-
return callback(error, connection);
166+
return next(error, connection);
155167
});
156168
}
157169

158-
function models(callback, data) {
159-
return callback(null);
170+
function models(next, data) {
171+
return next(null);
160172
}
161173

162-
function validators(callback, data) {
163-
var tv4 = require('tv4'),
174+
function validators(next, data) {
175+
var tv4 = require('tv4'), // Node module: https://github.com/geraintluff/tv4
164176
fs = require('fs');
165177
/**
166178
* Creates validator functions for input.
167179
* @param {String} file - The file path.
168180
* @param {Function} callback - The callback.
169181
*/
170-
function validatorFactory(file, callback) {
171-
fs.readFile('./schema/list.json', 'utf8', function (err, file) {
182+
function validatorFactory(filePath, callback) {
183+
fs.readFile(filePath, 'utf8', function (err, file) {
172184
if (err) { callback(err, null); }
173185
/**
174186
* Validates the data based on the schema.
@@ -182,18 +194,20 @@ function validators(callback, data) {
182194
});
183195
}
184196
async.parallel({
197+
// callbacks are implictly here
185198
item: _.partial(validatorFactory, './schema/item.json'),
186199
list: _.partial(validatorFactory, './schema/list.json')
187200
}, function finish(error, results) {
188-
callback(error, results);
201+
next(error, results);
202+
// Results is [function validateItem(data), function validateList(data)]
189203
});
190204
}
191205

192-
function routes(callback, data) {
206+
function routes(next, data) {
193207
var router = new require('express').Router();
194-
router.get('/auth', function (req, res, next) {
208+
router.get('/auth', function (req, res, callback) {
195209
console.error("Not implemented yet");
196-
next();
210+
callback();
197211
});
198212
router.get('/logout', function (req, res) {
199213
console.error("Logout called, but no auth implemented");
@@ -210,7 +224,7 @@ function routes(callback, data) {
210224
}
211225
);
212226
router.get('/visualization/:title',
213-
function (req, res, next) { console.error("Auth not implemented yet."); next(); },
227+
function (req, res, callback) { console.error("Auth not implemented yet."); callback(); },
214228
data.middleware.populateVisualization,
215229
data.middleware.populateVisualizationList,
216230
function render(req, res) {
@@ -225,7 +239,7 @@ function routes(callback, data) {
225239
);
226240
// Attach the router.
227241
data.httpd.use(router);
228-
callback(null, router);
242+
next(null, router);
229243
}
230244

231245
function complete(error, data) {

0 commit comments

Comments
 (0)