Skip to content

Commit

Permalink
[chore] split http request handlers out into their own file to simpli…
Browse files Browse the repository at this point in the history
…fy server.js took 4 mins. preparing for #23
  • Loading branch information
nelsonic committed May 1, 2017
1 parent c5a55f6 commit 994ccf4
Show file tree
Hide file tree
Showing 5 changed files with 81 additions and 61 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ so we will be able to re-use code
in the "Real" version of the Time app.
+ Most people in our organization are _familiar_/_experienced_
with these tools so the code in this MVP will be easy to understand.
+ We have a "Beginner Level" ***Tutorial*** `forEach` one
(_see links in each sub-section below_) so the learning curve is shallower.

### `Tachyons` for UI Consistency

Expand Down
10 changes: 6 additions & 4 deletions lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ function initialise_state() {
/**
* save state to localstorage so that we don't lose a timer on page refresh
*/
function save_state_to_localstorage() {
function save_store_to_localstorage() {
try { // see: http://diveintohtml5.info/detect.html#storage
if('localStorage' in window && window['localStorage'] !== null) {
localStorage.setItem('store', JSON.stringify(store));
Expand All @@ -60,8 +60,10 @@ function save_state_to_server() {
console.log('- - - - - - json:');
console.log(json);
store = json; // update the state session_id from server
save_state_to_localstorage();
save_store_to_localstorage();
if(window.location.href.indexOf('verify') > -1) {
store.verify_token = window.location.href.split('?')[1];
save_state_to_localstorage()
window.location.href = '/';
}
render_complete_table();
Expand Down Expand Up @@ -137,7 +139,7 @@ function start_timer() {
if (!timer_is_running()) {
store.timers.push({ start: Date.now() });
}
save_state_to_localstorage();
save_store_to_localstorage();
}

function clock() {
Expand Down Expand Up @@ -236,7 +238,7 @@ function save_email() {
var email = document.getElementById('email-address').value;
if (validate_email(email)) {
store.email_address = email;
save_state_to_localstorage();
save_store_to_localstorage();
save_state_to_server();
document.getElementById('register').classList.add('dn');
}
Expand Down
5 changes: 3 additions & 2 deletions lib/index.html
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Time MVP</title>
<link rel="shortcut icon" type="image/png" href="http://www.favicon.cc/logo3d/818488.png"/>
<title>Time MVP (Title Gets Over-ridden with Clock ;-)</title>
<link rel="shortcut icon" type="image/png"
href="https://cloud.githubusercontent.com/assets/194400/25605640/15c23162-2f04-11e7-8371-228cf5bf61e2.png"/>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/css/tachyons.min.css"/>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<script src="client.js"></script> <!-- load "client" application -->
Expand Down
62 changes: 62 additions & 0 deletions lib/request_handlers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
var fs = require('fs');
var path = require('path');
var db = require('./db.js');

function serve_index(req, res) {
return fs.readFile(path.resolve('./lib/index.html'), function (err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
});
}

function serve_client(req, res) {
return fs.readFile(path.resolve('./lib/client.js'), function (err, data) {
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.end(data);
});
}

function handle_post(req, res) {
var body = ''; // accumulate the HTTP POST body before attempting to process.
req.on('data', function (data) { body += data; });
req.on('end', function () {
try {
req.json = JSON.parse(body); // MVP!! (Don't Do this Kids!!)
} catch(e) { // in case for any reason the JSON from the client is malformed
console.warn('unable to parse the data received:', body)
res.writeHead(200, {'Content-Type': 'text/json'});
return res.end(body);
}
db.save_state(req, res, function(err, req, res){
res.writeHead(200, {'Content-Type': 'text/json'});
return res.end(JSON.stringify(req.json));
});
});
}

function handle_email_verification_request(req, res) {
if(req.headers.accept.indexOf('text/html') > -1) { // clicked link in email
db.check_verification_token(req, res, function(err, req, res) {
fs.readFile(path.resolve('./lib/index.html'), function (err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
});
});
}
else { // get existing state for client based on verification token
console.log('JSON "AJAX" request for /verify');
db.get_store_for_verification_token(req, res, function(err, req, res) {
res.writeHead(200, {'Content-Type': 'text/json'});
console.log('63 - - - - - - - - - - - -req.json:')
console.log(req.json)
return res.end(JSON.stringify(req.json));
});
}
}

module.exports = {
serve_index: serve_index,
serve_client: serve_client,
handle_post: handle_post,
handle_email_verification_request: handle_email_verification_request
}
63 changes: 8 additions & 55 deletions lib/server.js
Original file line number Diff line number Diff line change
@@ -1,68 +1,21 @@
var http = require('http');
var fs = require('fs');
var path = require('path');
var db = require('./db.js');
var handlers = require('./request_handlers.js');

http.createServer(function handler (req, res) {
console.log(req.method, ':', req.url);
url = req.url.split('?')[0];
http.createServer(function handler (req, res) { // can you make it simpler? ;-)
console.log(req.method, ':', req.url); // rudimentary request logging
var url = req.url.split('?')[0]; // strip query params for url routing
switch (url) {
case '/save':
handle_post(req, res)
handlers.handle_post(req, res);
break;
case '/verify':
handle_email_verification_request(req, res);
handlers.handle_email_verification_request(req, res);
break;
case '/client.js':
fs.readFile(path.resolve('./lib/client.js'), function (err, data) {
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.end(data);
});
handlers.serve_client(req, res);
break;
default:
fs.readFile(path.resolve('./lib/index.html'), function (err, data) {
// console.log('accept:', req.headers.accept);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
});
handlers.serve_index(req, res);
break;
}
}).listen(process.env.PORT); // start the server with the command: npm run dev

function handle_post(req, res) {
var body = ''; // accumulate the HTTP POST body before attempting to process.
req.on('data', function (data) { body += data; });
req.on('end', function () {
try {
req.json = JSON.parse(body); // MVP!! (Don't Do this Kids!!)
} catch(e) { // in case for any reason the JSON from the client is malformed
console.warn('unable to parse the data received:', body)
res.writeHead(200, {'Content-Type': 'text/json'});
return res.end(body);
}
db.save_state(req, res, function(err, req, res){
res.writeHead(200, {'Content-Type': 'text/json'});
return res.end(JSON.stringify(req.json));
});
});
}

function handle_email_verification_request(req, res) {
if(req.headers.accept.indexOf('text/html') > -1) { // clicked link in email
db.check_verification_token(req, res, function(err, req, res) {
fs.readFile(path.resolve('./lib/index.html'), function (err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
});
});
}
else { // get existing state for client based on verification token
console.log('JSON "AJAX" request for /verify');
db.get_store_for_verification_token(req, res, function(err, req, res) {
res.writeHead(200, {'Content-Type': 'text/json'});
console.log('63 - - - - - - - - - - - -req.json:')
console.log(req.json)
return res.end(JSON.stringify(req.json));
});
}
}

0 comments on commit 994ccf4

Please sign in to comment.