diff --git a/lab-shawn/.gitignore b/lab-shawn/.gitignore new file mode 100644 index 0000000..96bb76c --- /dev/null +++ b/lab-shawn/.gitignore @@ -0,0 +1,127 @@ +Created by https://www.gitignore.io/api/macos,node,vim,windows,linux + +out.bmp +### macOS ### +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon +# Thumbnails +._* +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + + +### Node ### +node_modules +# Logs +logs +*.log +npm-debug.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules +jspm_packages + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + + + +### Vim ### +# swap +[._]*.s[a-w][a-z] +[._]s[a-w][a-z] +# session +Session.vim +# temporary +.netrwhist +*~ +# auto-generated tag files +tags + + +### Windows ### +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + + +### Linux ### + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* diff --git a/lab-shawn/lib/parse-json.js b/lab-shawn/lib/parse-json.js new file mode 100644 index 0000000..8e23bab --- /dev/null +++ b/lab-shawn/lib/parse-json.js @@ -0,0 +1,25 @@ +'use strict'; + +module.exports = function(req){ + return new Promise((resolve,reject) => { + if(req.method === 'POST' || req.method === 'PUT'){ + var body = ''; + + req.on('data',data => { + body += data.toString(); + }); + + req.on('end', () =>{ + try{ + req.body = JSON.parse(body); + resolve(req); + }catch(err){ + console.error(err); + reject(err); + } + }); + return; + } + resolve(); + }); +} diff --git a/lab-shawn/lib/parse-url.js b/lab-shawn/lib/parse-url.js new file mode 100644 index 0000000..f9c85e5 --- /dev/null +++ b/lab-shawn/lib/parse-url.js @@ -0,0 +1,10 @@ +'use strict'; + +const parseUrl = require('url').parse; +const parseQuery = require('querystring').parse; + +module.exports = function(req){ + req.url = parseUrl(req.url); + req.url.query = parseQuery(req.url.query); + return Promise.resolve(req); +}; diff --git a/lab-shawn/lib/router.js b/lab-shawn/lib/router.js new file mode 100644 index 0000000..6dba04c --- /dev/null +++ b/lab-shawn/lib/router.js @@ -0,0 +1,56 @@ +'use strict'; + +const parseUrl = require('./parse-url.js'); +const parseJSON = require('./parse-json.js'); + +const Router = module.exports = function(){ + this.routes = { + GET: {}, + POST: {}, + PUT: {}, + DELETE: {} + }; +}; + +Router.prototype.get = function(endpoint,callback){ + this.routes.GET[endpoint] = callback; +}; + +Router.prototype.post = function(endpoint,callback){ + this.routes.POST[endpoint] = callback; +}; + +Router.prototype.put = function(endpoint,callback){ + this.routes.PUT[endpoint] = callback; +}; + +Router.prototype.delete = function(endpoint,callback){ + this.routes.DELETE[endpoint] = callback; +}; + +Router.prototype.route = function(){ + return (req,res) => { + Promise.all([ + parseUrl(req), + parseJSON(req) + ]) + .then( () => { + if(typeof this.routes[req.method][req.url.pathname] === 'function'){ + this.routes[req.method][req.url.pathname](req,res); + return; + } + + console.error('route not found'); + + res.writeHead(404,{'Content-Type':'text/plain'}); + res.write('route not found'); + res.end(); + }) + .catch(err => { + console.error(err); + res.writeHead(400, {'Content-Type': 'text/plain'}); + res.write('bad request'); + res.end(); + }); + }; +}; diff --git a/lab-shawn/lib/storage.js b/lab-shawn/lib/storage.js new file mode 100644 index 0000000..4cb4b0a --- /dev/null +++ b/lab-shawn/lib/storage.js @@ -0,0 +1,43 @@ +'use strict'; + +const storage = {}; + +module.exports = exports = {}; + +exports.createPerson = function(schemaName, person){ + if(!schemaName) return Promise.reject(new Error('expected schema name')); + if(!person) return Promise.reject(new Error('expected a person')); + if(!storage[schemaName]) storage[schemaName] = {}; + + storage[schemaName][person.id] = person; + return Promise.resolve(person); +}; + +exports.fetchPerson = function(schemaName,id){ + return new Promise((resolve,reject) => { + if(!schemaName) return reject(new Error('expected schema name')); + if(!id) return reject(new Error('expected an id')); + + var schema = storage[schemaName]; + if(!schema) return reject(new Error('schema not found')); + + var person = schema[id]; + if(!person) return reject(new Error('person not found')); + + resolve(person); + }); + +}; +exports.deletePerson = function(schemaName,id){ + return new Promise((resolve,reject) => { + if(!schemaName) return reject(new Error('expected schema name')); + if(!id) return reject(new Error('expected id')); + + var schema = storage[schemaName]; + if(!schema) return reject(new Error('schema not found')); + + delete schema[id]; + resolve(); + + }); +}; diff --git a/lab-shawn/model/person.js b/lab-shawn/model/person.js new file mode 100644 index 0000000..993e410 --- /dev/null +++ b/lab-shawn/model/person.js @@ -0,0 +1,12 @@ +'use strict'; + +const uuid = require('node-uuid'); + +module.exports = function(name, gender){ + if(!name) throw new Error('expected name'); + if(!gender) throw new Error('expected gender'); + + this.id = uuid.v1(); + this.name = name; + this.gender = gender; +} diff --git a/lab-shawn/package.json b/lab-shawn/package.json new file mode 100644 index 0000000..cbb5eb7 --- /dev/null +++ b/lab-shawn/package.json @@ -0,0 +1,24 @@ +{ + "name": "lab-shawn", + "version": "1.0.0", + "description": "", + "main": "server.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "start": "node server.js" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "node-uuid": "^1.4.7" + }, + "devDependencies": { + "chai": "^3.5.0", + "mocha": "^3.2.0", + "superagent": "^3.3.0" + } +} diff --git a/lab-shawn/server.js b/lab-shawn/server.js new file mode 100644 index 0000000..044399d --- /dev/null +++ b/lab-shawn/server.js @@ -0,0 +1,70 @@ +'use strict'; + +const http = require('http'); +const Person = require('./model/person.js'); +const Router = require('./lib/router.js'); +const storage = require('./lib/storage.js'); +const PORT = process.env.PORT || 3000; + +const router = new Router(); + +router.get('/api/person', function(req,res){ + if(!req.url.query.id){ + res.writeHead(400,{'Content-Type':'text/plain'}); + res.write('bad request'); + res.end(); + } + if(req.url.query.id){ + storage.fetchPerson('person',req.url.query.id) + .then( person => { + res.writeHead(200, {'Content-Type':'application/json'}); + res.write(JSON.stringify(person)); + res.end(); + }) + .catch(err => { + console.error(err); + res.writeHead(404,{'Content-Type':'text/plain'}); + res.write('person not found'); + res.end(); + }); + return; + } +}); + +router.post('/api/person',function(req,res){ + try{ + var person = new Person(req.body.name,req.body.gender); + storage.createPerson('person',person); + res.writeHead(200, {'Content-Type':'application/json'}); + res.write(JSON.stringify(person)); + res.end(); + }catch(err){ + console.error(err); + res.writeHead(400, {'Content-Type':'text/plain'}); + res.write('bad request'); + res.end(); + } +}); + +router.delete('/api/person', function(req,res){ + if(req.url.query.id){ + storage.deletePerson('person',req.url.query.id) + .then(person => { + res.writeHead(204,{'Content-Type':'application/json'}); + res.write('Person Removed'); + res.end(); + }) + .catch(err => { + console.error(err); + res.writeHead(404,{'Content-Type': 'text/plain'}); + res.write('person not found'); + res.end(); + }); + } +}); + +const server = http.createServer(router.route()); + +server.listen(PORT, () => { + console.log('Served On:', PORT); +}); diff --git a/lab-shawn/test/person-route-test.js b/lab-shawn/test/person-route-test.js new file mode 100644 index 0000000..cb29ae8 --- /dev/null +++ b/lab-shawn/test/person-route-test.js @@ -0,0 +1,57 @@ +'use strict'; + +const request = require('superagent'); +const expect = require('chai').expect; + +require('../server.js'); + +describe('Person Routes', function(){ + var person = null; + + describe('POST: /api/person', function(){ + it('should return a person', function(done){ + request.post('localhost:8000/api/person') + .send({name:'test name', gender:'male'}) + .end((err,res) => { + if(err) return done(err); + expect(res.status).to.equal(200); + person = res.body; + done(); + }); + }); + it('should return bad request', function(done){ + request.post('localhost:8000/api/person') + .send({name:'test name'}) + .end((err) => { + expect(err.status).to.equal(400); + done(); + }); + }); + }); + + describe('GET: /api/person', function(){ + it('should return with person', function(done){ + request.get(`localhost:8000/api/person?id=${person.id}`) + .end((err,res) => { + if(err) return done(err); + expect(res.status).to.equal(200); + person = res.body; + done(); + }); + }); + it('should return not found', function(done){ + request.get('localhost:8000/api/person?id=123') + .end((err) => { + expect(err.status).to.equal(404); + done(); + }); + }); + it('should return bad request', function(done){ + request.get('localhost:8000/api/person') + .end((err) => { + expect(err.status).to.equal(400); + done(); + }); + }); + }); +});