Created
March 6, 2015 03:59
-
-
Save nubunto/59ad7c2a7e716953daa9 to your computer and use it in GitHub Desktop.
database server, for the hacker school interview.
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
| // require the http module | |
| var http = require('http'); | |
| // require the util module to format things | |
| var util = require('util'); | |
| //the get regex matches /get and whatever and the set regex matches /set and whatever | |
| var getRegex = /\/get.*/, setRegex = /\/set.*/, database = {}; | |
| // create a server with the 'handler' function and start listening on 4000 | |
| http.createServer(handler).listen(4000); | |
| function handler(req, res) { | |
| // get the url and extract the params | |
| var url = req.url, urlParams = extract(url); | |
| // if there are any, | |
| if(urlParams) { | |
| // test to see if the url matches a set command | |
| if(setRegex.test(url)) { | |
| //if it does, update the database and let the user know what he did | |
| database[urlParams.key] = urlParams.value; | |
| res.end(util.format('you set \'%s\' to value %s', urlParams.key, urlParams.value)); | |
| } | |
| // test to see if it's a get command | |
| if(getRegex.test(url)) { | |
| // if it is, make sure the user is issuing the 'key' param, and get whatever's in the database. | |
| urlParams.key === 'key' && res.end(database[urlParams.value]); | |
| } | |
| } | |
| // if no route matches (or no criteria matches) get a friendly message to him. | |
| res.end(util.format('Hello! This is database server.\nUse /set?somekey=somevalue to map \'key\' to \'value\'\nand /get?key=somekey to get what\'s under the key \'key\'.')); | |
| } | |
| // the extract function receives a url and breaks it up to find the query string. | |
| function extract(url) { | |
| // first, extract what's after the '?' sign. | |
| // at the left, there is a route. at the right, what's after it | |
| // get the right and split it on '=', left is key, right is value. | |
| // if nothing is there, defaults to null. | |
| var params = url.indexOf('?') >= 0 ? url.split('?')[1].split('=') : null; | |
| // if there is something, return an object with the key and value as 'key' and 'value'. | |
| return params && { key: params[0], value: params[1] }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment