Created
October 26, 2013 17:03
-
-
Save ruzz311/7171941 to your computer and use it in GitHub Desktop.
Challenge 2. You should generate users.json from http://www.json-generator.com/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// responds to /users (returns users) | |
// post to { me: 'name', oldest: oldestId } to /oldest (checks against the oldest) | |
var http = require('http'), | |
url = require('url'), | |
users = require('./users.json'), | |
options = { port: 8000 }, | |
oldest = users[0]; | |
for (var i in users) { | |
if (users[i].age > oldest.age ) { | |
oldest = users[i]; | |
} | |
} | |
//console.log('oldest: ', JSON.stringify(oldest)); | |
function checkOldestUser (req, res) { | |
var obj, data = ''; | |
req.on('data', function (d) { data += d.toString(); }); | |
req.on('end', function(){ | |
obj = JSON.parse(data); | |
if(typeof obj.me !== 'undefined' && obj.oldest === oldest.id){ | |
res.write(obj.me+' figured it out! Good job! Fireworks and celebrations for you'); | |
} else if (obj.oldest === oldest.id) { | |
res.write('Someone found the oldest user but didn\'t provide a name. Try again!'); | |
} else if (typeof obj.me !== 'undefined') { | |
res.write('Getting closer '+obj.me+'... try again!'); | |
} else { | |
res.write('Not quite... try again!'); | |
} | |
res.end(); | |
}); | |
} | |
var server = http.createServer(function (req, res) { | |
res.statusCode = 200; | |
if (req.url === '/users') { | |
res.write(JSON.stringify(users)); | |
res.end(); | |
} else if (req.url === '/oldest' && req.method === 'POST') { | |
checkOldestUser(req,res); | |
} else { | |
res.write('Not a valid route, try again!' + req.method); | |
res.end(); | |
} | |
}).listen(options.port, function onStart () { | |
console.log('server started on port %s', options.port); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
json generator object: | |
[ | |
'{{repeat(10000, 10000)}}', | |
{ | |
id: '{{index}}', | |
age: '{{numeric(20, 100)}}', | |
name: '{{firstName}} {{surname}}' | |
} | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment