From 4a594dca252bb183ef2469441ea66c35903deab2 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Wed, 14 Dec 2016 22:07:23 -0800 Subject: [PATCH 01/49] scaffolding --- lab-jinho/.eslintrc | 21 +++++ lab-jinho/.gitignore | 146 ++++++++++++++++++++++++++++++ lab-jinho/README.md | 0 lab-jinho/gulpfile.js | 23 +++++ lab-jinho/lib/parse-json.js | 0 lab-jinho/lib/parse-url.js | 0 lab-jinho/lib/router.js | 0 lab-jinho/lib/storage.js | 0 lab-jinho/model/note.js | 0 lab-jinho/package.json | 23 +++++ lab-jinho/server.js | 0 lab-jinho/test/note-route-test.js | 0 12 files changed, 213 insertions(+) create mode 100644 lab-jinho/.eslintrc create mode 100644 lab-jinho/.gitignore create mode 100644 lab-jinho/README.md create mode 100644 lab-jinho/gulpfile.js create mode 100644 lab-jinho/lib/parse-json.js create mode 100644 lab-jinho/lib/parse-url.js create mode 100644 lab-jinho/lib/router.js create mode 100644 lab-jinho/lib/storage.js create mode 100644 lab-jinho/model/note.js create mode 100644 lab-jinho/package.json create mode 100644 lab-jinho/server.js create mode 100644 lab-jinho/test/note-route-test.js diff --git a/lab-jinho/.eslintrc b/lab-jinho/.eslintrc new file mode 100644 index 0000000..8dc6807 --- /dev/null +++ b/lab-jinho/.eslintrc @@ -0,0 +1,21 @@ +{ + "rules": { + "no-console": "off", + "indent": [ "error", 2 ], + "quotes": [ "error", "single" ], + "semi": ["error", "always"], + "linebreak-style": [ "error", "unix" ] + }, + "env": { + "es6": true, + "node": true, + "mocha": true, + "jasmine": true + }, + "ecmaFeatures": { + "modules": true, + "experimentalObjectRestSpread": true, + "impliedStrict": true + }, + "extends": "eslint:recommended" +} diff --git a/lab-jinho/.gitignore b/lab-jinho/.gitignore new file mode 100644 index 0000000..86d8c9c --- /dev/null +++ b/lab-jinho/.gitignore @@ -0,0 +1,146 @@ +Skip to content +This repository +Search +Pull requests +Issues +Gist + @jmpaik + Watch 5 + Star 1 + Fork 8 codefellows/seattle-javascript-401d12 + Code Issues 0 Pull requests 0 Projects 0 Wiki Pulse Graphs +Branch: master Find file Copy pathseattle-javascript-401d12/06-tcp_servers/demo/chat-server/.gitignore +78ba337 a day ago +@bnates bnates added lecture 06 +1 contributor +RawBlameHistory +128 lines (94 sloc) 1.85 KB +# Created by https://www.gitignore.io/api/node,vim,macos,linux,windows + +node_modules/ + +### Node ### +# 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 + + +### 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 + + +### 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* + + +### 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 +Contact GitHub API Training Shop Blog About +© 2016 GitHub, Inc. Terms Privacy Security Status Help diff --git a/lab-jinho/README.md b/lab-jinho/README.md new file mode 100644 index 0000000..e69de29 diff --git a/lab-jinho/gulpfile.js b/lab-jinho/gulpfile.js new file mode 100644 index 0000000..b16e376 --- /dev/null +++ b/lab-jinho/gulpfile.js @@ -0,0 +1,23 @@ +'use strict'; + +const gulp = require('gulp'); +const eslint = require('gulp-eslint'); +const mocha = require('gulp-mocha'); + +gulp.task('test', function(){ + gulp.src('./test/*-test.js', {read: false}) + .pipe(mocha({reporter: 'spec'})); +}); + +gulp.task('lint', function(){ + return gulp.src(['**/*.js','!node_modules/**']) + .pipe(eslint()) + .pipe(eslint.format()) + .pipe(eslint.failAfterError()); +}); + +gulp.task('dev', function(){ + gulp.watch(['**/*.js','!node_modules/**'], ['lint', 'test']); +}); + +gulp.task('default', ['dev']); diff --git a/lab-jinho/lib/parse-json.js b/lab-jinho/lib/parse-json.js new file mode 100644 index 0000000..e69de29 diff --git a/lab-jinho/lib/parse-url.js b/lab-jinho/lib/parse-url.js new file mode 100644 index 0000000..e69de29 diff --git a/lab-jinho/lib/router.js b/lab-jinho/lib/router.js new file mode 100644 index 0000000..e69de29 diff --git a/lab-jinho/lib/storage.js b/lab-jinho/lib/storage.js new file mode 100644 index 0000000..e69de29 diff --git a/lab-jinho/model/note.js b/lab-jinho/model/note.js new file mode 100644 index 0000000..e69de29 diff --git a/lab-jinho/package.json b/lab-jinho/package.json new file mode 100644 index 0000000..e5adadb --- /dev/null +++ b/lab-jinho/package.json @@ -0,0 +1,23 @@ +{ + "name": "lab-jinho", + "version": "1.0.0", + "description": "", + "main": "gulpfile.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", + "superagent": "^3.3.0" + } +} diff --git a/lab-jinho/server.js b/lab-jinho/server.js new file mode 100644 index 0000000..e69de29 diff --git a/lab-jinho/test/note-route-test.js b/lab-jinho/test/note-route-test.js new file mode 100644 index 0000000..e69de29 From 5c20099a17375c3ae4c09741a58f5d6d11bdcbab Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Wed, 14 Dec 2016 22:43:08 -0800 Subject: [PATCH 02/49] dependencies and start server --- lab-jinho/server.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/lab-jinho/server.js b/lab-jinho/server.js index e69de29..17609fb 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -0,0 +1,30 @@ +'use strict'; + +//**DEPENDENCIES** +//node modules +const http = require('http'); +//npm modules + +//custom modules +const Note = require('./model/note.js'); +const Router = require('./lib/router.js'); +const storage = require('./lib/storage.js'); +//environment variables +const PORT = process.env.PORT || 3000; +//module constants +const router = new Router(); + +//Logic: Method: GET + +//Logic: Method: POST + +//Logic: Method: DELETE + + + +//**START SERVER** +const server = http.createServer(router.route()); + +server.listen(PORT, () => { + console.log('server up:', PORT); +}); From c696d43a6b5c3192d2418be4d36b3f83b8d6394a Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Thu, 15 Dec 2016 10:36:43 -0800 Subject: [PATCH 03/49] parse json --- lab-jinho/lib/parse-json.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/lab-jinho/lib/parse-json.js b/lab-jinho/lib/parse-json.js index e69de29..631b1be 100644 --- a/lab-jinho/lib/parse-json.js +++ b/lab-jinho/lib/parse-json.js @@ -0,0 +1,32 @@ +'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); + }; + }); + + req.on('error', err => { + console.error(err); + reject(err); + }); + + return; + }; + + resolve(); + }); +}; From d6c10661406472bf23f55c6bd5e32ea57f3f1947 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Thu, 15 Dec 2016 10:39:53 -0800 Subject: [PATCH 04/49] parse url --- lab-jinho/lib/parse-url.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/lab-jinho/lib/parse-url.js b/lab-jinho/lib/parse-url.js index e69de29..bd4e014 100644 --- a/lab-jinho/lib/parse-url.js +++ b/lab-jinho/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); +}; From 362afd569371171e1321dfb5a7eee09ad6e124b1 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Thu, 15 Dec 2016 10:46:48 -0800 Subject: [PATCH 05/49] router --- lab-jinho/lib/router.js | 63 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/lab-jinho/lib/router.js b/lab-jinho/lib/router.js index e69de29..866b95f 100644 --- a/lab-jinho/lib/router.js +++ b/lab-jinho/lib/router.js @@ -0,0 +1,63 @@ +'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(); + }); + }; +}; From ba3fb105227b8d01d3256ac365893302faac941d Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Thu, 15 Dec 2016 10:48:43 -0800 Subject: [PATCH 06/49] storage --- lab-jinho/lib/storage.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/lab-jinho/lib/storage.js b/lab-jinho/lib/storage.js index e69de29..24df6cc 100644 --- a/lab-jinho/lib/storage.js +++ b/lab-jinho/lib/storage.js @@ -0,0 +1,30 @@ +'use strict'; + +const storage = {}; + +module.exports = exports = {}; + +exports.createItem = function(schemaName, item) { + if (!schemaName) return Promise.reject(new Error('expected schemaName')); + if (!item) return Promise.reject(new Error('expected item')); + if (!storage[schemaName]) storage[schemaName] = {}; + + storage[schemaName][item.id] = item; + + return Promise.resolve(item); +}; + +exports.fetchItem = 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')); + + var item = schema[id]; + if (!item) return reject(new Error('item not found')); + + resolve(item); + }); +}; From c59ee7aea4e570caa98db2833b7a013d2d69d9dd Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Thu, 15 Dec 2016 10:51:16 -0800 Subject: [PATCH 07/49] node uuid in note.js --- lab-jinho/model/note.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/lab-jinho/model/note.js b/lab-jinho/model/note.js index e69de29..e601dd6 100644 --- a/lab-jinho/model/note.js +++ b/lab-jinho/model/note.js @@ -0,0 +1,12 @@ +'use strict'; + +const uuid = require('node-uuid'); + +module.exports = function(name, content) { + if (!name) throw new Error('expected name'); + if (!content) throw new Error('expected content'); + + this.id = uuid.v1(); + this.name = name; + this.content = content; +}; From 7288d900ed3e0c3384ea18bba1a30d45375d32ad Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Thu, 15 Dec 2016 10:52:45 -0800 Subject: [PATCH 08/49] router GET --- lab-jinho/server.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 17609fb..5276ace 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -15,6 +15,27 @@ const PORT = process.env.PORT || 3000; const router = new Router(); //Logic: Method: GET +router.get('/api/note', function(req, res) { + if (req.url.query.id) { + storage.fetchItem('note', req.url.query.id) + .then( note => { + res.writeHead(200, { + 'Content-Type': 'application/json' + }); + res.write(JSON.stringify(note)); + res.end(); + }) + .catch( err => { + console.error(err); + res.writeHead(404, { + 'Content-Type': 'text/plain' + }); + res.write('not found'); + res.end(); + }); + + return; + }; //Logic: Method: POST From acff9f42249dfc2c42d387c825d589d61f29f761 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Thu, 15 Dec 2016 10:56:20 -0800 Subject: [PATCH 09/49] router POST --- lab-jinho/server.js | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 5276ace..1afd6d4 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -37,8 +37,32 @@ router.get('/api/note', function(req, res) { return; }; -//Logic: Method: POST + res.writeHead(400, { + 'Content-Type': 'text/plain' + }); + res.write('bad request'); + res.end(); +}); +//Logic: Method: POST +router.post('/api/note', function(req, res) { + try { + var note = new Note(req.body.name, req.body.content); + storage.createItem('note', note); + res.writeHead(200, { + 'Content-Type': 'application/json' + }); + res.write(JSON.stringify(note)); + res.end(); + } catch (err) { + console.error(err); + res.writeHead(400, { + 'Content-Type': 'text/plain' + }); + res.write('bad request'); + res.end(); + }; +}); //Logic: Method: DELETE From 4984d43261a82e779169a002c5ca7aa4f5dd7fc8 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Thu, 15 Dec 2016 11:01:37 -0800 Subject: [PATCH 10/49] router DELETE --- lab-jinho/server.js | 40 ++++++++++++++++++++++++---------------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 1afd6d4..645aa35 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -19,17 +19,13 @@ router.get('/api/note', function(req, res) { if (req.url.query.id) { storage.fetchItem('note', req.url.query.id) .then( note => { - res.writeHead(200, { - 'Content-Type': 'application/json' - }); + res.writeHead(200, {'Content-Type': 'application/json'}); res.write(JSON.stringify(note)); res.end(); }) .catch( err => { console.error(err); - res.writeHead(404, { - 'Content-Type': 'text/plain' - }); + res.writeHead(404, {'Content-Type': 'text/plain'}); res.write('not found'); res.end(); }); @@ -37,9 +33,7 @@ router.get('/api/note', function(req, res) { return; }; - res.writeHead(400, { - 'Content-Type': 'text/plain' - }); + res.writeHead(400, {'Content-Type': 'text/plain'}); res.write('bad request'); res.end(); }); @@ -49,22 +43,36 @@ router.post('/api/note', function(req, res) { try { var note = new Note(req.body.name, req.body.content); storage.createItem('note', note); - res.writeHead(200, { - 'Content-Type': 'application/json' - }); + res.writeHead(200, {'Content-Type': 'application/json'}); res.write(JSON.stringify(note)); res.end(); } catch (err) { console.error(err); - res.writeHead(400, { - 'Content-Type': 'text/plain' - }); + res.writeHead(400, {'Content-Type': 'text/plain'}); res.write('bad request'); res.end(); }; }); //Logic: Method: DELETE - +router.delete('/api/note', function(req, res) { + if (req.url.query.id) { + storage.deleteItem('note', req.url.query.id) + .then(() => { + res.writeHead(200, {'Content-Type': 'application/json'}); + res.end(); + }) + .catch( err => { + console.error(err); + res.writeHead(404, {'Content-Type': 'text/plain'}); + res.write('not found'); + res.end(); + }); + return; + } + res.writeHead(400, {'Content-Type': 'text/plain',}); + res.write('bad request'); + res.end(); +}); //**START SERVER** From 87406605e250b9f3a047a4fc9274969aaf0069ea Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Thu, 15 Dec 2016 11:09:24 -0800 Subject: [PATCH 11/49] add DELETE method in server and storage --- lab-jinho/lib/storage.js | 12 ++++++++++++ lab-jinho/server.js | 1 + 2 files changed, 13 insertions(+) diff --git a/lab-jinho/lib/storage.js b/lab-jinho/lib/storage.js index 24df6cc..dcd4f38 100644 --- a/lab-jinho/lib/storage.js +++ b/lab-jinho/lib/storage.js @@ -28,3 +28,15 @@ exports.fetchItem = function(schemaName, id) { resolve(item); }); }; + +exports.deleteItem = 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')); + + if(!storage[schemaName]) return reject(new Error('schema not found')); + if(!storage[schemaName][id]) return reject(new Error('item not found')); + + if(storage[schemaName][id]) resolve(delete (storage[schemaName][id])); + }); +}; diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 645aa35..705c720 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -53,6 +53,7 @@ router.post('/api/note', function(req, res) { res.end(); }; }); + //Logic: Method: DELETE router.delete('/api/note', function(req, res) { if (req.url.query.id) { From 9123260bbdde8e7b1fa3e0e28e0f9c02d5a5c537 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Thu, 15 Dec 2016 11:15:26 -0800 Subject: [PATCH 12/49] minor edit in server and started testing --- lab-jinho/server.js | 2 +- lab-jinho/test/note-route-test.js | 38 +++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 705c720..cbd1f2c 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -59,7 +59,7 @@ router.delete('/api/note', function(req, res) { if (req.url.query.id) { storage.deleteItem('note', req.url.query.id) .then(() => { - res.writeHead(200, {'Content-Type': 'application/json'}); + res.writeHead(204, {'Content-Type': 'application/json'}); res.end(); }) .catch( err => { diff --git a/lab-jinho/test/note-route-test.js b/lab-jinho/test/note-route-test.js index e69de29..1df0ca9 100644 --- a/lab-jinho/test/note-route-test.js +++ b/lab-jinho/test/note-route-test.js @@ -0,0 +1,38 @@ +'use strict'; + +const request = require('superagent'); +const expect = require('chai').expect; + +require('../server.js'); + +describe('Note Routes', function() { + var note = null; + + describe('POST: /api/note', function() { + it('should return a note', function(done) { + request.post('localhost:3000/api/note') + .send({ name: 'test name', content: 'test content' }) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal('test name'); + expect(res.body.content).to.equal('test content'); + note = res.body; + done(); + }); + }); + }); + + describe('GET: /api/note', function() { + it('should return a note', function(done) { + request.get(`localhost:3000/api/note?id=${note.id}`) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal('test name'); + expect(res.body.content).to.equal('test content'); + done(); + }); + }); + }); +}); From 4f146b66a5095de9884e00eca5a2dfc62553382e Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Thu, 15 Dec 2016 21:27:58 -0800 Subject: [PATCH 13/49] add bluebird and testing branch PR --- lab-jinho/package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/lab-jinho/package.json b/lab-jinho/package.json index e5adadb..d12cde8 100644 --- a/lab-jinho/package.json +++ b/lab-jinho/package.json @@ -14,6 +14,7 @@ "author": "", "license": "ISC", "dependencies": { + "bluebird": "^3.4.6", "node-uuid": "^1.4.7" }, "devDependencies": { From 90ce984da5a91ed9add9e17cf7ebd97e4a92da3f Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Fri, 16 Dec 2016 10:37:11 -0800 Subject: [PATCH 14/49] changed note properties and finished testing --- lab-jinho/model/note.js | 10 +++---- lab-jinho/server.js | 2 +- lab-jinho/test/note-route-test.js | 47 +++++++++++++++++++++++++++---- 3 files changed, 48 insertions(+), 11 deletions(-) diff --git a/lab-jinho/model/note.js b/lab-jinho/model/note.js index e601dd6..f5c40bd 100644 --- a/lab-jinho/model/note.js +++ b/lab-jinho/model/note.js @@ -2,11 +2,11 @@ const uuid = require('node-uuid'); -module.exports = function(name, content) { - if (!name) throw new Error('expected name'); - if (!content) throw new Error('expected content'); +module.exports = function(restaurantname, address) { + if (!restaurantname) throw new Error('expected restaurant name'); + if (!address) throw new Error('expected address'); this.id = uuid.v1(); - this.name = name; - this.content = content; + this.restaurantname = restaurantname; + this.address = address; }; diff --git a/lab-jinho/server.js b/lab-jinho/server.js index cbd1f2c..2aeebad 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -41,7 +41,7 @@ router.get('/api/note', function(req, res) { //Logic: Method: POST router.post('/api/note', function(req, res) { try { - var note = new Note(req.body.name, req.body.content); + var note = new Note(req.body.restaurantname, req.body.address); storage.createItem('note', note); res.writeHead(200, {'Content-Type': 'application/json'}); res.write(JSON.stringify(note)); diff --git a/lab-jinho/test/note-route-test.js b/lab-jinho/test/note-route-test.js index 1df0ca9..f9044f7 100644 --- a/lab-jinho/test/note-route-test.js +++ b/lab-jinho/test/note-route-test.js @@ -8,29 +8,66 @@ require('../server.js'); describe('Note Routes', function() { var note = null; +//POST: test 400 should respond with 'bad request' if no request body was provided or body was invalid + describe('POST: /api/note', function(){ + it('respond with bad request - POST', function(done){ + request.post('localhost:3000/api/note') + .send({invalid:'invalid body'}) + .end((err, res) => { + expect(res.status).to.equal(400); + expect(res.text).to.be.equal('bad request'); + done(); + }); + }); + }); +//POST: test 200 should respond with the body content for post request with valid body describe('POST: /api/note', function() { it('should return a note', function(done) { request.post('localhost:3000/api/note') - .send({ name: 'test name', content: 'test content' }) + .send({restaurantname: 'test restaurant name', address: 'test address'}) .end((err, res) => { if (err) return done(err); expect(res.status).to.equal(200); - expect(res.body.name).to.equal('test name'); - expect(res.body.content).to.equal('test content'); + expect(res.body.restaurantname).to.equal('test restaurant name'); + expect(res.body.address).to.equal('test address'); note = res.body; done(); }); }); }); +//GET: test 404 should respond with 'not found' for valid requests made with id not found + describe('GET: /api/note', function(){ + it('return error for no id valid request - GET', function(done){ + request.get('localhost:3000/api/note?id=123') + .end((err, res) => { + expect(res.status).to.equal(404); + expect(res.text).to.equal('not found'); + done(); + }); + }); + }); + +//GET: test 400 should respond with 'bad request' if no id was provided in request + describe('GET: /api/note', function(){ + it('return error with no id - GET', function(done){ + request.get('localhost:3000/api/note') + .end((err, res) => { + expect(res.status).to.equal(400); + expect(res.text).to.equal('bad request'); + done(); + }); + }); + }); +//GET: test 200 should contain response body for request made with valid id describe('GET: /api/note', function() { it('should return a note', function(done) { request.get(`localhost:3000/api/note?id=${note.id}`) .end((err, res) => { if (err) return done(err); expect(res.status).to.equal(200); - expect(res.body.name).to.equal('test name'); - expect(res.body.content).to.equal('test content'); + expect(res.body.restaurantname).to.equal('test restaurant name'); + expect(res.body.address).to.equal('test address'); done(); }); }); From 78781102772b7794f919cf784e26e904e45e7b72 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Fri, 16 Dec 2016 11:02:43 -0800 Subject: [PATCH 15/49] refactoring route responses --- lab-jinho/lib/response.js | 15 +++++++ lab-jinho/route/note-route.js | 67 +++++++++++++++++++++++++++++++ lab-jinho/server.js | 66 +----------------------------- lab-jinho/test/note-route-test.js | 4 +- 4 files changed, 85 insertions(+), 67 deletions(-) create mode 100644 lab-jinho/lib/response.js create mode 100644 lab-jinho/route/note-route.js diff --git a/lab-jinho/lib/response.js b/lab-jinho/lib/response.js new file mode 100644 index 0000000..2ac599d --- /dev/null +++ b/lab-jinho/lib/response.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = exports = {}; + +exports.sendJSON = function(res, status, data) { + res.writeHead(status, {'Content-Type': 'application/json'}); + res.write(JSON.stringify(data)); + res.end(); +}; + +exports.sendText = function(res, status, msg) { + res.writeHead(status, {'Content-Type': 'text/plain'}); + res.write(msg); + res.end(); +}; diff --git a/lab-jinho/route/note-route.js b/lab-jinho/route/note-route.js new file mode 100644 index 0000000..aa3541c --- /dev/null +++ b/lab-jinho/route/note-route.js @@ -0,0 +1,67 @@ +'use strict'; + +const storage = require('../lib/storage.js'); +const Note = require('../model/note.js'); +const response = require('../lib/response.js'); + +module.exports = function(router) { + + //Logic: Method: GET + router.get('/api/note', function(req, res) { + if (req.url.query.id) { + storage.fetchItem('note', req.url.query.id) + .then( note => { + res.writeHead(200, {'Content-Type': 'application/json'}); + res.write(JSON.stringify(note)); + res.end(); + }) + .catch( err => { + console.error(err); + res.writeHead(404, {'Content-Type': 'text/plain'}); + res.write('not found'); + res.end(); + }); + + return; + } + + res.writeHead(400, {'Content-Type': 'text/plain'}); + res.write('bad request'); + res.end(); + }); + //Logic: Method: POST + router.post('/api/note', function(req, res) { + try { + var note = new Note(req.body.restaurantname, req.body.address); + storage.createItem('note', note); + res.writeHead(200, {'Content-Type': 'application/json'}); + res.write(JSON.stringify(note)); + res.end(); + } catch (err) { + console.error(err); + res.writeHead(400, {'Content-Type': 'text/plain'}); + res.write('bad request'); + res.end(); + } + }); + //Logic: Method: DELETE + router.delete('/api/note', function(req, res) { + if (req.url.query.id) { + storage.deleteItem('note', req.url.query.id) + .then(() => { + res.writeHead(204, {'Content-Type': 'application/json'}); + res.end(); + }) + .catch( err => { + console.error(err); + res.writeHead(404, {'Content-Type': 'text/plain'}); + res.write('not found'); + res.end(); + }); + return; + } + res.writeHead(400, {'Content-Type': 'text/plain',}); + res.write('bad request'); + res.end(); + }); +}; diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 2aeebad..54b6340 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -6,76 +6,14 @@ const http = require('http'); //npm modules //custom modules -const Note = require('./model/note.js'); const Router = require('./lib/router.js'); -const storage = require('./lib/storage.js'); + //environment variables const PORT = process.env.PORT || 3000; //module constants const router = new Router(); -//Logic: Method: GET -router.get('/api/note', function(req, res) { - if (req.url.query.id) { - storage.fetchItem('note', req.url.query.id) - .then( note => { - res.writeHead(200, {'Content-Type': 'application/json'}); - res.write(JSON.stringify(note)); - res.end(); - }) - .catch( err => { - console.error(err); - res.writeHead(404, {'Content-Type': 'text/plain'}); - res.write('not found'); - res.end(); - }); - - return; - }; - - res.writeHead(400, {'Content-Type': 'text/plain'}); - res.write('bad request'); - res.end(); -}); - -//Logic: Method: POST -router.post('/api/note', function(req, res) { - try { - var note = new Note(req.body.restaurantname, req.body.address); - storage.createItem('note', note); - res.writeHead(200, {'Content-Type': 'application/json'}); - res.write(JSON.stringify(note)); - res.end(); - } catch (err) { - console.error(err); - res.writeHead(400, {'Content-Type': 'text/plain'}); - res.write('bad request'); - res.end(); - }; -}); - -//Logic: Method: DELETE -router.delete('/api/note', function(req, res) { - if (req.url.query.id) { - storage.deleteItem('note', req.url.query.id) - .then(() => { - res.writeHead(204, {'Content-Type': 'application/json'}); - res.end(); - }) - .catch( err => { - console.error(err); - res.writeHead(404, {'Content-Type': 'text/plain'}); - res.write('not found'); - res.end(); - }); - return; - } - res.writeHead(400, {'Content-Type': 'text/plain',}); - res.write('bad request'); - res.end(); -}); - - +require('./route/note-route.js')(router); //**START SERVER** const server = http.createServer(router.route()); diff --git a/lab-jinho/test/note-route-test.js b/lab-jinho/test/note-route-test.js index f9044f7..bccb877 100644 --- a/lab-jinho/test/note-route-test.js +++ b/lab-jinho/test/note-route-test.js @@ -15,7 +15,7 @@ describe('Note Routes', function() { .send({invalid:'invalid body'}) .end((err, res) => { expect(res.status).to.equal(400); - expect(res.text).to.be.equal('bad request'); + expect(res.text).to.equal('bad request'); done(); }); }); @@ -35,7 +35,6 @@ describe('Note Routes', function() { }); }); }); - //GET: test 404 should respond with 'not found' for valid requests made with id not found describe('GET: /api/note', function(){ it('return error for no id valid request - GET', function(done){ @@ -47,7 +46,6 @@ describe('Note Routes', function() { }); }); }); - //GET: test 400 should respond with 'bad request' if no id was provided in request describe('GET: /api/note', function(){ it('return error with no id - GET', function(done){ From e4c40a40ff5f242c51abea4aada9f6951b089e11 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Fri, 16 Dec 2016 11:09:55 -0800 Subject: [PATCH 16/49] response refactor complete --- lab-jinho/route/note-route.js | 26 +++++++------------------- 1 file changed, 7 insertions(+), 19 deletions(-) diff --git a/lab-jinho/route/note-route.js b/lab-jinho/route/note-route.js index aa3541c..7837f58 100644 --- a/lab-jinho/route/note-route.js +++ b/lab-jinho/route/note-route.js @@ -5,43 +5,33 @@ const Note = require('../model/note.js'); const response = require('../lib/response.js'); module.exports = function(router) { - + //Logic: Method: GET router.get('/api/note', function(req, res) { if (req.url.query.id) { storage.fetchItem('note', req.url.query.id) .then( note => { - res.writeHead(200, {'Content-Type': 'application/json'}); - res.write(JSON.stringify(note)); - res.end(); + response.sendJSON(res, 200, note); }) .catch( err => { console.error(err); - res.writeHead(404, {'Content-Type': 'text/plain'}); - res.write('not found'); - res.end(); + response.sendText(res, 404, 'not found'); }); return; } - res.writeHead(400, {'Content-Type': 'text/plain'}); - res.write('bad request'); - res.end(); + response.sendText(res, 400, 'bad request'); }); //Logic: Method: POST router.post('/api/note', function(req, res) { try { var note = new Note(req.body.restaurantname, req.body.address); storage.createItem('note', note); - res.writeHead(200, {'Content-Type': 'application/json'}); - res.write(JSON.stringify(note)); - res.end(); + response.sendJSON(res, 200, note); } catch (err) { console.error(err); - res.writeHead(400, {'Content-Type': 'text/plain'}); - res.write('bad request'); - res.end(); + response.sendText(res, 400, 'bad request'); } }); //Logic: Method: DELETE @@ -60,8 +50,6 @@ module.exports = function(router) { }); return; } - res.writeHead(400, {'Content-Type': 'text/plain',}); - res.write('bad request'); - res.end(); + response.sendText(res, 400, 'bad request'); }); }; From 495b740def8c77dae587b9abc2a4eba1b98bbcd0 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Fri, 16 Dec 2016 11:15:57 -0800 Subject: [PATCH 17/49] refactoring storage --- lab-jinho/lib/parse-json.js | 4 ++-- lab-jinho/lib/storage.js | 24 +++++++++++------------- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/lab-jinho/lib/parse-json.js b/lab-jinho/lib/parse-json.js index 631b1be..07ebad7 100644 --- a/lab-jinho/lib/parse-json.js +++ b/lab-jinho/lib/parse-json.js @@ -16,7 +16,7 @@ module.exports = function(req) { } catch (err) { console.error(err); reject(err); - }; + } }); req.on('error', err => { @@ -25,7 +25,7 @@ module.exports = function(req) { }); return; - }; + } resolve(); }); diff --git a/lab-jinho/lib/storage.js b/lab-jinho/lib/storage.js index dcd4f38..8735cd9 100644 --- a/lab-jinho/lib/storage.js +++ b/lab-jinho/lib/storage.js @@ -7,11 +7,11 @@ module.exports = exports = {}; exports.createItem = function(schemaName, item) { if (!schemaName) return Promise.reject(new Error('expected schemaName')); if (!item) return Promise.reject(new Error('expected item')); - if (!storage[schemaName]) storage[schemaName] = {}; - storage[schemaName][item.id] = item; - - return Promise.resolve(item); + let json = JSON.stringify(item); + return fs.writeFileProm(`${__dirname}/../data/${schemaName}/${item.id}.json`, json) + .then( () => item) + .catch( err => Promise.reject(err)); }; exports.fetchItem = function(schemaName, id) { @@ -19,15 +19,13 @@ exports.fetchItem = function(schemaName, id) { 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')); - - var item = schema[id]; - if (!item) return reject(new Error('item not found')); - - resolve(item); - }); -}; + return fs.readFileProm(`${__dirname}/../data/${id}.json`) + .then(data => { + let item = JSON.parse(data.toString()); + return item; + }) + .catch( err => Promise.reject(err)); + } exports.deleteItem = function(schemaName, id){ return new Promise((resolve, reject) => { From 591e1a5483360939aa6359545ed3ca32acd131a7 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Fri, 16 Dec 2016 11:21:49 -0800 Subject: [PATCH 18/49] completed storage refactor --- lab-jinho/lib/storage.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/lab-jinho/lib/storage.js b/lab-jinho/lib/storage.js index 8735cd9..920f734 100644 --- a/lab-jinho/lib/storage.js +++ b/lab-jinho/lib/storage.js @@ -32,9 +32,5 @@ exports.deleteItem = function(schemaName, id){ if (!schemaName) return reject(new Error('expected schema name')); if (!id) return reject(new Error('expected id')); - if(!storage[schemaName]) return reject(new Error('schema not found')); - if(!storage[schemaName][id]) return reject(new Error('item not found')); - - if(storage[schemaName][id]) resolve(delete (storage[schemaName][id])); - }); + return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${item.id}.json`, json); }; From 95c454e1d01e7bf6c098414d589bc3c64842c04b Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 19 Dec 2016 12:16:15 -0800 Subject: [PATCH 19/49] major debugging --- lab-jinho/lib/storage.js | 25 ++++++++--------- lab-jinho/model/{note.js => restaurant.js} | 0 .../{note-route.js => restaurant-route.js} | 28 +++++++++---------- lab-jinho/server.js | 2 +- ...route-test.js => restaurant-route-test.js} | 28 +++++++++---------- 5 files changed, 41 insertions(+), 42 deletions(-) rename lab-jinho/model/{note.js => restaurant.js} (100%) rename lab-jinho/route/{note-route.js => restaurant-route.js} (56%) rename lab-jinho/test/{note-route-test.js => restaurant-route-test.js} (74%) diff --git a/lab-jinho/lib/storage.js b/lab-jinho/lib/storage.js index 920f734..ee63411 100644 --- a/lab-jinho/lib/storage.js +++ b/lab-jinho/lib/storage.js @@ -1,7 +1,7 @@ 'use strict'; -const storage = {}; - +const bluebird = require('bluebird'); +const fs = bluebird.promisifyAll(require('fs'), {suffix: "Prom"}); module.exports = exports = {}; exports.createItem = function(schemaName, item) { @@ -15,22 +15,21 @@ exports.createItem = function(schemaName, item) { }; exports.fetchItem = 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')); + // return new Promise((resolve, reject) => { + if (!schemaName) return Promise.reject(new Error('expected schema name')); + if (!id) return Promise.reject(new Error('expected id')); - return fs.readFileProm(`${__dirname}/../data/${id}.json`) + return fs.readFileProm(`${__dirname}/../data/${schemaName}/${id}.json`) .then(data => { - let item = JSON.parse(data.toString()); - return item; + let item = JSON.parse(data.toString()); + return Promise.resolve(item); }) .catch( err => Promise.reject(err)); - } +}; exports.deleteItem = 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')); + if (!schemaName) return Promise.reject(new Error('expected schema name')); + if (!id) return Promise.reject(new Error('expected id')); - return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${item.id}.json`, json); + return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`); }; diff --git a/lab-jinho/model/note.js b/lab-jinho/model/restaurant.js similarity index 100% rename from lab-jinho/model/note.js rename to lab-jinho/model/restaurant.js diff --git a/lab-jinho/route/note-route.js b/lab-jinho/route/restaurant-route.js similarity index 56% rename from lab-jinho/route/note-route.js rename to lab-jinho/route/restaurant-route.js index 7837f58..a9de9ce 100644 --- a/lab-jinho/route/note-route.js +++ b/lab-jinho/route/restaurant-route.js @@ -1,20 +1,20 @@ 'use strict'; const storage = require('../lib/storage.js'); -const Note = require('../model/note.js'); +const Restaurant = require('../model/restaurant.js'); const response = require('../lib/response.js'); module.exports = function(router) { //Logic: Method: GET - router.get('/api/note', function(req, res) { + router.get('/api/restaurant', function(req, res) { if (req.url.query.id) { - storage.fetchItem('note', req.url.query.id) - .then( note => { - response.sendJSON(res, 200, note); + storage.fetchItem('restaurant', req.url.query.id) + .then( restaurant => { + response.sendJSON(res, 200, restaurant); }) .catch( err => { - console.error(err); + // console.error(err); response.sendText(res, 404, 'not found'); }); @@ -24,26 +24,26 @@ module.exports = function(router) { response.sendText(res, 400, 'bad request'); }); //Logic: Method: POST - router.post('/api/note', function(req, res) { + router.post('/api/restaurant', function(req, res) { try { - var note = new Note(req.body.restaurantname, req.body.address); - storage.createItem('note', note); - response.sendJSON(res, 200, note); + var restaurant = new Restaurant(req.body.restaurantname, req.body.address); + storage.createItem('restaurant', restaurant); + response.sendJSON(res, 200, restaurant); } catch (err) { - console.error(err); + // console.error(err); response.sendText(res, 400, 'bad request'); } }); //Logic: Method: DELETE - router.delete('/api/note', function(req, res) { + router.delete('/api/restaurant', function(req, res) { if (req.url.query.id) { - storage.deleteItem('note', req.url.query.id) + storage.deleteItem('restaurant', req.url.query.id) .then(() => { res.writeHead(204, {'Content-Type': 'application/json'}); res.end(); }) .catch( err => { - console.error(err); + // console.error(err); res.writeHead(404, {'Content-Type': 'text/plain'}); res.write('not found'); res.end(); diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 54b6340..3b9043e 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -13,7 +13,7 @@ const PORT = process.env.PORT || 3000; //module constants const router = new Router(); -require('./route/note-route.js')(router); +require('./route/restaurant-route.js')(router); //**START SERVER** const server = http.createServer(router.route()); diff --git a/lab-jinho/test/note-route-test.js b/lab-jinho/test/restaurant-route-test.js similarity index 74% rename from lab-jinho/test/note-route-test.js rename to lab-jinho/test/restaurant-route-test.js index bccb877..796e044 100644 --- a/lab-jinho/test/note-route-test.js +++ b/lab-jinho/test/restaurant-route-test.js @@ -5,11 +5,11 @@ const expect = require('chai').expect; require('../server.js'); -describe('Note Routes', function() { - var note = null; +describe('Restaurant Routes', function() { + var restaurant = null; //POST: test 400 should respond with 'bad request' if no request body was provided or body was invalid - describe('POST: /api/note', function(){ + describe('POST: /api/restaurant', function(){ it('respond with bad request - POST', function(done){ request.post('localhost:3000/api/note') .send({invalid:'invalid body'}) @@ -21,24 +21,24 @@ describe('Note Routes', function() { }); }); //POST: test 200 should respond with the body content for post request with valid body - describe('POST: /api/note', function() { - it('should return a note', function(done) { - request.post('localhost:3000/api/note') + describe('POST: /api/restaurant', function() { + it('should return a restaurant', function(done) { + request.post('localhost:3000/api/restaurant') .send({restaurantname: 'test restaurant name', address: 'test address'}) .end((err, res) => { if (err) return done(err); expect(res.status).to.equal(200); expect(res.body.restaurantname).to.equal('test restaurant name'); expect(res.body.address).to.equal('test address'); - note = res.body; + restaurant = res.body; done(); }); }); }); //GET: test 404 should respond with 'not found' for valid requests made with id not found - describe('GET: /api/note', function(){ + describe('GET: /api/restaurant', function(){ it('return error for no id valid request - GET', function(done){ - request.get('localhost:3000/api/note?id=123') + request.get('localhost:3000/api/restaurant?id=123') .end((err, res) => { expect(res.status).to.equal(404); expect(res.text).to.equal('not found'); @@ -47,9 +47,9 @@ describe('Note Routes', function() { }); }); //GET: test 400 should respond with 'bad request' if no id was provided in request - describe('GET: /api/note', function(){ + describe('GET: /api/restaurant', function(){ it('return error with no id - GET', function(done){ - request.get('localhost:3000/api/note') + request.get('localhost:3000/api/restaurant') .end((err, res) => { expect(res.status).to.equal(400); expect(res.text).to.equal('bad request'); @@ -58,9 +58,9 @@ describe('Note Routes', function() { }); }); //GET: test 200 should contain response body for request made with valid id - describe('GET: /api/note', function() { - it('should return a note', function(done) { - request.get(`localhost:3000/api/note?id=${note.id}`) + describe('GET: /api/restaurant', function() { + it('should return a restaurant', function(done) { + request.get(`localhost:3000/api/restaurant?id=${restaurant.id}`) .end((err, res) => { if (err) return done(err); expect(res.status).to.equal(200); From 012fd19b06fa6835515e4d12b686668f7455774d Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 19 Dec 2016 12:18:59 -0800 Subject: [PATCH 20/49] weird DS store --- .DS_Store | Bin 0 -> 6148 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..f5a011f8c0cf181313bceb53685072c954e46a2c GIT binary patch literal 6148 zcmeHK%Wl&^6upxMYOAWq0;yfj28l(e+?J9`6_ORoqC2D@SWuMObwrFDPh>kpZ3yyj zz#s4_d;y;WXC8@K+KNquM0Kxp=iGUmJMtNO#zRD+J4v>QT14c*H8y+{*O>0te#IKD zr3n-!M?m}3r<8J(Z2yA-dhH}-6j4l1=;Hc~Xh0)URL~h#vp}sxZGz|&aUYB^R(cC# zlA}zW#+izdOTS15@W;Q5AtLgZ`9GR>V@T=`#`nK7;%PZ{bNq@KZEan)mLn zdcN=Z>)!j`P)&PPR87imRJ=2_G#SJ$eyvotjHCEXI+*rb4_~Ofiqd>gTo``*Hq8?? z?W#$hlqS!ss2YN6ChE5~XS1EXy|&!x1oO6>bvi*?KHYsbpL^cMqwVKMC!@3T+2{F} zujcVd;Nvj%z~KVEA-G1IPrV|~RQ>_I3+95s$O^CmtiY`(;5HX;?N+jJ5>|i}xJwG? z{XxPth7N0sX6ryw0(VLQ(LC%OcJWB= zY`yYu`mB}k6Sy`#uC} Aq5uE@ literal 0 HcmV?d00001 From 0ccd393116f06cfd458e4aadf982c48dcea778d4 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 19 Dec 2016 12:31:47 -0800 Subject: [PATCH 21/49] finished readme --- lab-jinho/README.md | 89 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/lab-jinho/README.md b/lab-jinho/README.md index e69de29..e8170bc 100644 --- a/lab-jinho/README.md +++ b/lab-jinho/README.md @@ -0,0 +1,89 @@ +# Vanilla-REST-API +============= + +structures : +- lib + - parse-json.js + - parse-url.js + - storage.js + - router.js +- model + - restaurant.js +- test + - restaurant-route-test.js +- root + - server.js + - gulpfile.js + - .gitignore + - .eslintrc + - README.md + +## Getting Started +- In terminal enter : node server.js +- also you can run gulp +- for tests in terminal enter: + - gulp OR mocha + + +### Prerequisities + +- dependencies: + +``` +npm install -S node-uuid +npm install -S superagent + +``` + +- devDependencies: + +``` +npm install -D gulp-eslint +npm install -D gulp-mocha +npm install -D mocha +npm install -D gulp +npm install -D chai + +``` + +## Running + +- In your root server, type in the command **"node server.js"** in your terminal. +- OR in terminal type: gulp + + +- GET request: + ```http localhost:3000/api/restaurant?id=selectedId ``` + +- POST request: + ```http POST localhost:3000/api/restaurant restaurantname="name of restaurant" address="location address" ``` + +- DELETE request: + ```http DELETE localhost:3000/api/person?id=selectedId ``` + +## Testing: +- we have 5 tests for GET and POST requests : + - test to ensure that API returns a status code of 404 for routes that have not been registered + - tests to ensure that **/api/restaurant** endpoint responds as described for each condition below: + - GET - test 404, responds with 'not found' for valid request made with an id that was not found + - GET - test 400, responds with 'bad request' if no id was provided in the request + - GET - test 200, response body like {} for a request made with a valid id + - POST - test 400, responds with 'bad request' for if no body provided or invalid body + - POST - test 200, response body like {} for a post request with a valid body + +## Built With: + +* Nodejs +* JavaScript + +## Versioning + +Not Applicable + +## Authors + +* **BlueToad** - [Github](https://github.com/jmpaik) + +## License + +None. From 248664f02c2e6d1256259efd1147ecd1b6ced19c Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 19 Dec 2016 12:35:38 -0800 Subject: [PATCH 22/49] syntax error fix in storage --- lab-jinho/lib/storage.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lab-jinho/lib/storage.js b/lab-jinho/lib/storage.js index ee63411..22f3716 100644 --- a/lab-jinho/lib/storage.js +++ b/lab-jinho/lib/storage.js @@ -1,7 +1,7 @@ 'use strict'; const bluebird = require('bluebird'); -const fs = bluebird.promisifyAll(require('fs'), {suffix: "Prom"}); +const fs = bluebird.promisifyAll(require('fs'), {suffix: 'Prom'}); module.exports = exports = {}; exports.createItem = function(schemaName, item) { From f389ae335b8385776388373cfaa35984af9c740b Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 19 Dec 2016 13:02:27 -0800 Subject: [PATCH 23/49] fixed syntax error in tests --- lab-jinho/test/restaurant-route-test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lab-jinho/test/restaurant-route-test.js b/lab-jinho/test/restaurant-route-test.js index 796e044..4ccd721 100644 --- a/lab-jinho/test/restaurant-route-test.js +++ b/lab-jinho/test/restaurant-route-test.js @@ -11,7 +11,7 @@ describe('Restaurant Routes', function() { //POST: test 400 should respond with 'bad request' if no request body was provided or body was invalid describe('POST: /api/restaurant', function(){ it('respond with bad request - POST', function(done){ - request.post('localhost:3000/api/note') + request.post('localhost:3000/api/restaurant') .send({invalid:'invalid body'}) .end((err, res) => { expect(res.status).to.equal(400); From 0d9baa6ef0caed35b7076fba80ba71c5d2915ae0 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 19 Dec 2016 13:15:30 -0800 Subject: [PATCH 24/49] edit README file --- lab-jinho/README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lab-jinho/README.md b/lab-jinho/README.md index e8170bc..cddce26 100644 --- a/lab-jinho/README.md +++ b/lab-jinho/README.md @@ -2,11 +2,15 @@ ============= structures : +- data + - restaurant + - random item - lib - parse-json.js - parse-url.js - - storage.js + - response.js - router.js + - storage.js - model - restaurant.js - test From 2812292a52b95bc30e171e4ee805a0a18c7d3a35 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 19 Dec 2016 14:23:49 -0800 Subject: [PATCH 25/49] begin express refactor --- lab-jinho/lib/parse-json.js | 32 --------------- lab-jinho/lib/parse-url.js | 10 ----- lab-jinho/lib/response.js | 15 ------- lab-jinho/lib/router.js | 63 ----------------------------- lab-jinho/package.json | 6 ++- lab-jinho/route/restaurant-route.js | 55 ------------------------- lab-jinho/server.js | 31 ++++++++++---- 7 files changed, 29 insertions(+), 183 deletions(-) delete mode 100644 lab-jinho/lib/parse-json.js delete mode 100644 lab-jinho/lib/parse-url.js delete mode 100644 lab-jinho/lib/response.js delete mode 100644 lab-jinho/lib/router.js delete mode 100644 lab-jinho/route/restaurant-route.js diff --git a/lab-jinho/lib/parse-json.js b/lab-jinho/lib/parse-json.js deleted file mode 100644 index 07ebad7..0000000 --- a/lab-jinho/lib/parse-json.js +++ /dev/null @@ -1,32 +0,0 @@ -'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); - } - }); - - req.on('error', err => { - console.error(err); - reject(err); - }); - - return; - } - - resolve(); - }); -}; diff --git a/lab-jinho/lib/parse-url.js b/lab-jinho/lib/parse-url.js deleted file mode 100644 index bd4e014..0000000 --- a/lab-jinho/lib/parse-url.js +++ /dev/null @@ -1,10 +0,0 @@ -'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-jinho/lib/response.js b/lab-jinho/lib/response.js deleted file mode 100644 index 2ac599d..0000000 --- a/lab-jinho/lib/response.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -module.exports = exports = {}; - -exports.sendJSON = function(res, status, data) { - res.writeHead(status, {'Content-Type': 'application/json'}); - res.write(JSON.stringify(data)); - res.end(); -}; - -exports.sendText = function(res, status, msg) { - res.writeHead(status, {'Content-Type': 'text/plain'}); - res.write(msg); - res.end(); -}; diff --git a/lab-jinho/lib/router.js b/lab-jinho/lib/router.js deleted file mode 100644 index 866b95f..0000000 --- a/lab-jinho/lib/router.js +++ /dev/null @@ -1,63 +0,0 @@ -'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-jinho/package.json b/lab-jinho/package.json index d12cde8..714b07a 100644 --- a/lab-jinho/package.json +++ b/lab-jinho/package.json @@ -8,13 +8,17 @@ }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1", - "start": "node server.js" + "start": "DEBUG='restaurant*' node server.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { + "Express": "^3.0.1", "bluebird": "^3.4.6", + "body-parser": "^1.15.2", + "express": "^4.14.0", + "morgan": "^1.7.0", "node-uuid": "^1.4.7" }, "devDependencies": { diff --git a/lab-jinho/route/restaurant-route.js b/lab-jinho/route/restaurant-route.js deleted file mode 100644 index a9de9ce..0000000 --- a/lab-jinho/route/restaurant-route.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -const storage = require('../lib/storage.js'); -const Restaurant = require('../model/restaurant.js'); -const response = require('../lib/response.js'); - -module.exports = function(router) { - - //Logic: Method: GET - router.get('/api/restaurant', function(req, res) { - if (req.url.query.id) { - storage.fetchItem('restaurant', req.url.query.id) - .then( restaurant => { - response.sendJSON(res, 200, restaurant); - }) - .catch( err => { - // console.error(err); - response.sendText(res, 404, 'not found'); - }); - - return; - } - - response.sendText(res, 400, 'bad request'); - }); - //Logic: Method: POST - router.post('/api/restaurant', function(req, res) { - try { - var restaurant = new Restaurant(req.body.restaurantname, req.body.address); - storage.createItem('restaurant', restaurant); - response.sendJSON(res, 200, restaurant); - } catch (err) { - // console.error(err); - response.sendText(res, 400, 'bad request'); - } - }); - //Logic: Method: DELETE - router.delete('/api/restaurant', function(req, res) { - if (req.url.query.id) { - storage.deleteItem('restaurant', req.url.query.id) - .then(() => { - res.writeHead(204, {'Content-Type': 'application/json'}); - res.end(); - }) - .catch( err => { - // console.error(err); - res.writeHead(404, {'Content-Type': 'text/plain'}); - res.write('not found'); - res.end(); - }); - return; - } - response.sendText(res, 400, 'bad request'); - }); -}; diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 3b9043e..12c9f8f 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -2,21 +2,38 @@ //**DEPENDENCIES** //node modules -const http = require('http'); +const express = require('express'); +const morgan = require('morgan'); +const createError = require('http-errors'); +const jsonParser = require('body-parser').json(); +const debug = require('debug')('restaurant:server'); + +const app = express(); +const Restaurant = require('./model/restaurant.js'); +const storage = require('./lib/storage.js'); //npm modules //custom modules -const Router = require('./lib/router.js'); + //environment variables const PORT = process.env.PORT || 3000; //module constants -const router = new Router(); -require('./route/restaurant-route.js')(router); + + //**START SERVER** -const server = http.createServer(router.route()); +app.use(morgan('dev')); + +app.get('/test', function(req, res) { + debug('debug test route'); + res.json({ 'msg': 'test route worked'}); +}); + +app.post('/api/restaurant', function(req, res, next) { + +}); -server.listen(PORT, () => { - console.log('server up:', PORT); +app.listen(PORT, () => { + console.log(`server up: ${PORT}`); }); From a9e2ba5b5c51dfe6074fd211488b4e4836bd727b Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 19 Dec 2016 14:36:31 -0800 Subject: [PATCH 26/49] refactor restaurant file --- lab-jinho/model/restaurant.js | 12 +++++++++++- lab-jinho/server.js | 5 +++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/lab-jinho/model/restaurant.js b/lab-jinho/model/restaurant.js index f5c40bd..a9f918e 100644 --- a/lab-jinho/model/restaurant.js +++ b/lab-jinho/model/restaurant.js @@ -1,8 +1,13 @@ 'use strict'; const uuid = require('node-uuid'); +const createError = require('http-errors'); +const debug = require('debug')('restaurant:restaurant'); +const storage = require('../lib/storage.js'); + +const Restaurant = module.exports = function(restaurantname, address) { + debug('restaurant constructor'); -module.exports = function(restaurantname, address) { if (!restaurantname) throw new Error('expected restaurant name'); if (!address) throw new Error('expected address'); @@ -10,3 +15,8 @@ module.exports = function(restaurantname, address) { this.restaurantname = restaurantname; this.address = address; }; + +Restaurant.createRestaurant = function(_restaurant) { + debug('createRestaurant'); + +}; diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 12c9f8f..1a320b6 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -30,8 +30,9 @@ app.get('/test', function(req, res) { res.json({ 'msg': 'test route worked'}); }); -app.post('/api/restaurant', function(req, res, next) { - +app.post('/api/restaurant', jsonParser, function(req, res, next) { + debug('POST: /api/restaurant'); + // TODO: build post route }); app.listen(PORT, () => { From 9e8a1fdf065f15a63e8d5e3b1ab33d53d56fce77 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 19 Dec 2016 14:44:06 -0800 Subject: [PATCH 27/49] added create and fectch method in restaurant file --- lab-jinho/model/restaurant.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/lab-jinho/model/restaurant.js b/lab-jinho/model/restaurant.js index a9f918e..1a36089 100644 --- a/lab-jinho/model/restaurant.js +++ b/lab-jinho/model/restaurant.js @@ -18,5 +18,16 @@ const Restaurant = module.exports = function(restaurantname, address) { Restaurant.createRestaurant = function(_restaurant) { debug('createRestaurant'); - + + try { + let restaurant = new Restaurant(_restaurant.restaurantname, _restaurant.address); + return storage.createItem('restaurant', restaurant); + } catch (err) { + return Promise.reject(err); + } +}; + +Restaurant.fetchRestaurant = function(id) { + debug('fetchRestaurant'); + return storage.fetchItem('restaurant', id); }; From 4248f4295b9faeaa635fe32eac74f20c3221eb58 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 19 Dec 2016 14:50:10 -0800 Subject: [PATCH 28/49] build POST in server file --- lab-jinho/server.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 1a320b6..f3c0535 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -32,7 +32,10 @@ app.get('/test', function(req, res) { app.post('/api/restaurant', jsonParser, function(req, res, next) { debug('POST: /api/restaurant'); - // TODO: build post route + + Restaurant.createRestaurant(req.body) + .then( restaurant => res.json(restaurant)) + .catch( err => next(err)); }); app.listen(PORT, () => { From da3911a13697fb7ed6dc22eabf515f25df9aceb3 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 19 Dec 2016 18:53:16 -0800 Subject: [PATCH 29/49] debug createError in storage --- lab-jinho/lib/storage.js | 35 ++++++++++++++++++++++++----------- lab-jinho/model/restaurant.js | 6 +++--- lab-jinho/server.js | 28 +++++++++++++++++++++++++--- 3 files changed, 52 insertions(+), 17 deletions(-) diff --git a/lab-jinho/lib/storage.js b/lab-jinho/lib/storage.js index 22f3716..1812db8 100644 --- a/lab-jinho/lib/storage.js +++ b/lab-jinho/lib/storage.js @@ -1,30 +1,43 @@ 'use strict'; -const bluebird = require('bluebird'); -const fs = bluebird.promisifyAll(require('fs'), {suffix: 'Prom'}); +const Promise = require('bluebird'); +const fs = Promise.promisifyAll(require('fs'), {suffix: 'Prom'}); +const createError = require('http-errors'); +const debug = require('debug')('restaurant:storage'); + +const storage = {}; + + module.exports = exports = {}; exports.createItem = function(schemaName, item) { - if (!schemaName) return Promise.reject(new Error('expected schemaName')); - if (!item) return Promise.reject(new Error('expected item')); + debug('createItem'); + + if (!schemaName) return Promise.reject(createError(400, 'expected schemaName')); + if (!item) return Promise.reject(createError(400, 'expected item')); let json = JSON.stringify(item); return fs.writeFileProm(`${__dirname}/../data/${schemaName}/${item.id}.json`, json) .then( () => item) - .catch( err => Promise.reject(err)); + .catch( err => Promise.reject(createError(500, err.message))); }; exports.fetchItem = function(schemaName, id) { - // return new Promise((resolve, reject) => { - if (!schemaName) return Promise.reject(new Error('expected schema name')); - if (!id) return Promise.reject(new Error('expected id')); + debug('fetchItem'); + + if (!schemaName) return Promise.reject(createError(400, 'expected schema name')); + if (!id) return Promise.reject(createError(400, 'expected id')); return fs.readFileProm(`${__dirname}/../data/${schemaName}/${id}.json`) .then(data => { - let item = JSON.parse(data.toString()); - return Promise.resolve(item); + try { + let item = JSON.parse(data.toString()); + return item; + } catch (err) { + return Promise.reject(createError(500, err.message)); + } }) - .catch( err => Promise.reject(err)); + .catch(err => Promise.reject(createError(404, err.message))); }; exports.deleteItem = function(schemaName, id){ diff --git a/lab-jinho/model/restaurant.js b/lab-jinho/model/restaurant.js index 1a36089..ec12749 100644 --- a/lab-jinho/model/restaurant.js +++ b/lab-jinho/model/restaurant.js @@ -7,9 +7,9 @@ const storage = require('../lib/storage.js'); const Restaurant = module.exports = function(restaurantname, address) { debug('restaurant constructor'); - - if (!restaurantname) throw new Error('expected restaurant name'); - if (!address) throw new Error('expected address'); + //TODO: createError + if (!restaurantname) throw createError(400, 'expected restaurant name'); + if (!address) throw createError(400, 'expected address'); this.id = uuid.v1(); this.restaurantname = restaurantname; diff --git a/lab-jinho/server.js b/lab-jinho/server.js index f3c0535..8e85cbb 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -8,7 +8,6 @@ const createError = require('http-errors'); const jsonParser = require('body-parser').json(); const debug = require('debug')('restaurant:server'); -const app = express(); const Restaurant = require('./model/restaurant.js'); const storage = require('./lib/storage.js'); //npm modules @@ -18,6 +17,7 @@ const storage = require('./lib/storage.js'); //environment variables const PORT = process.env.PORT || 3000; +const app = express(); //module constants @@ -26,8 +26,8 @@ const PORT = process.env.PORT || 3000; app.use(morgan('dev')); app.get('/test', function(req, res) { - debug('debug test route'); - res.json({ 'msg': 'test route worked'}); + debug('debugging test route'); + res.json({ 'msg': 'test route works'}); }); app.post('/api/restaurant', jsonParser, function(req, res, next) { @@ -38,6 +38,28 @@ app.post('/api/restaurant', jsonParser, function(req, res, next) { .catch( err => next(err)); }); +app.get('/api/restaurant', function(req, res, next) { + debug('GET: /api/restaurant'); + + Restaurant.fetchRestaurant(req.query.id) + .then( restaurant => res.json(restaurant)) + .catch( err => next(err)); +}); + +app.use(function(err, req, res, next) { + debug('error middleware'); + console.error(err.message); + + if (err.status) { + res.status(err.status).send(err.name); + return; + } + + err = createError(500, err.message); + res.status(err.status).send(err.name); +}); + + app.listen(PORT, () => { console.log(`server up: ${PORT}`); }); From db96422f4a34463212e4a8218c563858341a43c3 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 19 Dec 2016 18:59:25 -0800 Subject: [PATCH 30/49] added delete to storage with debug --- lab-jinho/lib/storage.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lab-jinho/lib/storage.js b/lab-jinho/lib/storage.js index 1812db8..913be79 100644 --- a/lab-jinho/lib/storage.js +++ b/lab-jinho/lib/storage.js @@ -41,8 +41,10 @@ exports.fetchItem = function(schemaName, id) { }; exports.deleteItem = function(schemaName, id){ - if (!schemaName) return Promise.reject(new Error('expected schema name')); - if (!id) return Promise.reject(new Error('expected id')); + debug('deleteItem'); + + if (!schemaName) return Promise.reject(createError(400, 'expected schema name')); + if (!id) return Promise.reject(createError(400, 'expected id')); return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`); }; From 7fb9b822b83232a2dd47091ee653e707c0d5d1f7 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 19 Dec 2016 20:51:27 -0800 Subject: [PATCH 31/49] debugging delete in server.js --- lab-jinho/model/restaurant.js | 7 ++++++- lab-jinho/server.js | 8 ++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lab-jinho/model/restaurant.js b/lab-jinho/model/restaurant.js index ec12749..b2b5ddb 100644 --- a/lab-jinho/model/restaurant.js +++ b/lab-jinho/model/restaurant.js @@ -7,7 +7,7 @@ const storage = require('../lib/storage.js'); const Restaurant = module.exports = function(restaurantname, address) { debug('restaurant constructor'); - //TODO: createError + if (!restaurantname) throw createError(400, 'expected restaurant name'); if (!address) throw createError(400, 'expected address'); @@ -31,3 +31,8 @@ Restaurant.fetchRestaurant = function(id) { debug('fetchRestaurant'); return storage.fetchItem('restaurant', id); }; + +Restaurant.deleteRestaurant = function(schemaName, id) { + debug('deleteRestaurant'); + return storage.deleteItem('restaurant', id); +}; diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 8e85cbb..5967792 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -46,6 +46,13 @@ app.get('/api/restaurant', function(req, res, next) { .catch( err => next(err)); }); +app.delete('/api/restaurant', function(req, res, next) { + debug('DELETE: /api/restaurant'); + + Restaurant.deleteRestaurant('restaurant', req.query.id); + +}); + app.use(function(err, req, res, next) { debug('error middleware'); console.error(err.message); @@ -57,6 +64,7 @@ app.use(function(err, req, res, next) { err = createError(500, err.message); res.status(err.status).send(err.name); + }); From 0ef2fbaa4279bd1c5a6c8f16aeb7df6b31754281 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Tue, 20 Dec 2016 09:41:51 -0800 Subject: [PATCH 32/49] fixed delete function in server --- lab-jinho/server.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 5967792..9713cf5 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -49,8 +49,9 @@ app.get('/api/restaurant', function(req, res, next) { app.delete('/api/restaurant', function(req, res, next) { debug('DELETE: /api/restaurant'); - Restaurant.deleteRestaurant('restaurant', req.query.id); - + Restaurant.deleteRestaurant('restaurant', req.query.id) + .then( () => res.status(204).send()) + .catch( err => next(err)); }); app.use(function(err, req, res, next) { From 621363b7591821e2e3e48da1e623fda53be20ee2 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Tue, 20 Dec 2016 10:16:48 -0800 Subject: [PATCH 33/49] debugged tests to comply with express messaging --- lab-jinho/server.js | 1 - lab-jinho/test/restaurant-route-test.js | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 9713cf5..c8e7a7c 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -56,7 +56,6 @@ app.delete('/api/restaurant', function(req, res, next) { app.use(function(err, req, res, next) { debug('error middleware'); - console.error(err.message); if (err.status) { res.status(err.status).send(err.name); diff --git a/lab-jinho/test/restaurant-route-test.js b/lab-jinho/test/restaurant-route-test.js index 4ccd721..37c4e7d 100644 --- a/lab-jinho/test/restaurant-route-test.js +++ b/lab-jinho/test/restaurant-route-test.js @@ -15,7 +15,7 @@ describe('Restaurant Routes', function() { .send({invalid:'invalid body'}) .end((err, res) => { expect(res.status).to.equal(400); - expect(res.text).to.equal('bad request'); + expect(res.text).to.equal('BadRequestError'); done(); }); }); @@ -41,7 +41,7 @@ describe('Restaurant Routes', function() { request.get('localhost:3000/api/restaurant?id=123') .end((err, res) => { expect(res.status).to.equal(404); - expect(res.text).to.equal('not found'); + expect(res.text).to.equal('NotFoundError'); done(); }); }); @@ -52,7 +52,7 @@ describe('Restaurant Routes', function() { request.get('localhost:3000/api/restaurant') .end((err, res) => { expect(res.status).to.equal(400); - expect(res.text).to.equal('bad request'); + expect(res.text).to.equal('BadRequestError'); done(); }); }); From f82811d25fbae932493829c9b57fe8c3c9e56396 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Tue, 20 Dec 2016 10:29:26 -0800 Subject: [PATCH 34/49] deleted const storage in server --- lab-jinho/server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lab-jinho/server.js b/lab-jinho/server.js index c8e7a7c..6036065 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -9,7 +9,6 @@ const jsonParser = require('body-parser').json(); const debug = require('debug')('restaurant:server'); const Restaurant = require('./model/restaurant.js'); -const storage = require('./lib/storage.js'); //npm modules //custom modules @@ -54,6 +53,7 @@ app.delete('/api/restaurant', function(req, res, next) { .catch( err => next(err)); }); +// eslint-disable-next-line app.use(function(err, req, res, next) { debug('error middleware'); From 3c913118b37e1a291cee7d6f0db7a363362c84c6 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Tue, 20 Dec 2016 15:25:15 -0800 Subject: [PATCH 35/49] refactoring express api --- lab-jinho/lib/cors-middleware.js | 7 ++++ lab-jinho/lib/error-middleware.js | 21 ++++++++++ lab-jinho/lib/storage.js | 9 +++- lab-jinho/model/restaurant.js | 21 +++++++++- lab-jinho/package.json | 5 ++- lab-jinho/route/restaurant-router.js | 43 +++++++++++++++++++ lab-jinho/server.js | 56 ++++++------------------- lab-jinho/test/restaurant-route-test.js | 8 +++- 8 files changed, 123 insertions(+), 47 deletions(-) create mode 100644 lab-jinho/lib/cors-middleware.js create mode 100644 lab-jinho/lib/error-middleware.js create mode 100644 lab-jinho/route/restaurant-router.js diff --git a/lab-jinho/lib/cors-middleware.js b/lab-jinho/lib/cors-middleware.js new file mode 100644 index 0000000..6661797 --- /dev/null +++ b/lab-jinho/lib/cors-middleware.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function(req, res, next) { + res.append('Access-Control-Allow-Origin', '*'); + res.append('Access-Control-Allow-Headers', '*'); + next(); +}; diff --git a/lab-jinho/lib/error-middleware.js b/lab-jinho/lib/error-middleware.js new file mode 100644 index 0000000..96a627a --- /dev/null +++ b/lab-jinho/lib/error-middleware.js @@ -0,0 +1,21 @@ +'use strict'; + +const createError = require('http-errors'); +const debug = require('debug')('restaurant:error-middleware'); + +module.exports = function(err, req, res, next) { + console.error(err.message); + + if (err.status) { + debug('user error'); + + res.status(err.status).send(err.name); + next(); + return; + } + + debug('server error'); + err = createError(500, err.message); + res.status(err.status).send(err.name); + next(); +}; diff --git a/lab-jinho/lib/storage.js b/lab-jinho/lib/storage.js index 913be79..b13130f 100644 --- a/lab-jinho/lib/storage.js +++ b/lab-jinho/lib/storage.js @@ -46,5 +46,12 @@ exports.deleteItem = function(schemaName, id){ if (!schemaName) return Promise.reject(createError(400, 'expected schema name')); if (!id) return Promise.reject(createError(400, 'expected id')); - return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`); + return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`) + .catch( err => Promise.reject(createError(404, err.message))); +}; + +exports.availIDs = function(schemaName) { + return fs.readdirProm(`${__dirname}/../data/${schemaName}`) + .then( files => files.map(name => name.split('.json')[0])) + .catch( err => Promise.reject(createError(404, err.message))); }; diff --git a/lab-jinho/model/restaurant.js b/lab-jinho/model/restaurant.js index b2b5ddb..104bee3 100644 --- a/lab-jinho/model/restaurant.js +++ b/lab-jinho/model/restaurant.js @@ -23,7 +23,7 @@ Restaurant.createRestaurant = function(_restaurant) { let restaurant = new Restaurant(_restaurant.restaurantname, _restaurant.address); return storage.createItem('restaurant', restaurant); } catch (err) { - return Promise.reject(err); + return Promise.reject(createError(400, err.message)); } }; @@ -32,7 +32,26 @@ Restaurant.fetchRestaurant = function(id) { return storage.fetchItem('restaurant', id); }; +Restaurant.updateRestaurant = function(id, _restaurant) { + debug('updateRestaurant'); + + return storage.fetchItem('restaurant', id) + .catch(err => Promise.reject(createError(404, err.message))) + .then( restaurant => { + for (var prop in restaurant) { + if (prop === 'id') continue; + if (_restaurant[prop]) restaurant[prop] = _restaurant[prop]; + } + return storage.createItem('restaurant', restaurant); + }); +}; + Restaurant.deleteRestaurant = function(schemaName, id) { debug('deleteRestaurant'); return storage.deleteItem('restaurant', id); }; + +Restaurant.fetchIDs = function() { + debug('fetchIDs'); + return storage.availIDs('restaurant'); +}; diff --git a/lab-jinho/package.json b/lab-jinho/package.json index 714b07a..0bd6c38 100644 --- a/lab-jinho/package.json +++ b/lab-jinho/package.json @@ -7,7 +7,7 @@ "test": "test" }, "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", + "test": "DEBUG='restaurant*' mocha", "start": "DEBUG='restaurant*' node server.js" }, "keywords": [], @@ -17,12 +17,15 @@ "Express": "^3.0.1", "bluebird": "^3.4.6", "body-parser": "^1.15.2", + "debug": "^2.4.5", "express": "^4.14.0", + "http-errors": "^1.5.1", "morgan": "^1.7.0", "node-uuid": "^1.4.7" }, "devDependencies": { "chai": "^3.5.0", + "mocha": "^3.2.0", "superagent": "^3.3.0" } } diff --git a/lab-jinho/route/restaurant-router.js b/lab-jinho/route/restaurant-router.js new file mode 100644 index 0000000..c8449d2 --- /dev/null +++ b/lab-jinho/route/restaurant-router.js @@ -0,0 +1,43 @@ +'use strict'; + +const Router = require('express').Router; +const jsonParser = require('body-parser').json(); +const debug = require('debug')('restaurant:restaurant-router'); +const Restaurant = require('../model/restaurant.js'); +const restaurantRouter = new Router(); + +restaurantRouter.post('/api/restaurant', jsonParser, function(req, res, next) { + debug('POST: /api/restaurant'); + + Restaurant.createRestaurant(req.body) + .then( restaurant => res.json(restaurant)) + .catch( err => next(err)); +}); + +restaurantRouter.get('/api/restaurant/:id', function(req, res, next) { + debug('GET: /api/restaurant/:id'); + + Restaurant.fetchRestaurant(req.params.id) + .then( restaurant => res.json(restaurant)) + .catch( err => next(err)); +}); + +restaurantRouter.get('/api/restaurant', function(req, res, next) { + debug('GET: /api/restaurant'); + + Restaurant.fetchIDs() + .then( ids => res.json(ids)) + .catch(next); +}); + +restaurantRouter.put('/api/restaurant', jsonParser, function(req, res, next) { + debug('PUT: /api/restaurant'); + + Restaurant.updateRestaurant(req.query.id, req.body) + .then( restaurant => res.json(restaurant)) + .catch(next); +}); + + + +module.exports = restaurantRouter; diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 6036065..f9617d2 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -5,10 +5,10 @@ const express = require('express'); const morgan = require('morgan'); const createError = require('http-errors'); -const jsonParser = require('body-parser').json(); const debug = require('debug')('restaurant:server'); - -const Restaurant = require('./model/restaurant.js'); +const cors = require('./lib/cors-middleware.js'); +const errors = require('./lib/error-middleware.js'); +const restaurantRouter = require('./route/restaurantRouter.js'); //npm modules //custom modules @@ -23,49 +23,19 @@ const app = express(); //**START SERVER** app.use(morgan('dev')); +app.use(cors); +app.use(errors); +app.use(restaurantRouter); -app.get('/test', function(req, res) { - debug('debugging test route'); - res.json({ 'msg': 'test route works'}); -}); - -app.post('/api/restaurant', jsonParser, function(req, res, next) { - debug('POST: /api/restaurant'); - - Restaurant.createRestaurant(req.body) - .then( restaurant => res.json(restaurant)) - .catch( err => next(err)); -}); - -app.get('/api/restaurant', function(req, res, next) { - debug('GET: /api/restaurant'); - - Restaurant.fetchRestaurant(req.query.id) - .then( restaurant => res.json(restaurant)) - .catch( err => next(err)); -}); - -app.delete('/api/restaurant', function(req, res, next) { - debug('DELETE: /api/restaurant'); - - Restaurant.deleteRestaurant('restaurant', req.query.id) - .then( () => res.status(204).send()) - .catch( err => next(err)); -}); -// eslint-disable-next-line -app.use(function(err, req, res, next) { - debug('error middleware'); - if (err.status) { - res.status(err.status).send(err.name); - return; - } - - err = createError(500, err.message); - res.status(err.status).send(err.name); - -}); +// app.delete('/api/restaurant', function(req, res, next) { +// debug('DELETE: /api/restaurant'); +// +// Restaurant.deleteRestaurant('restaurant', req.query.id) +// .then( () => res.status(204).send()) +// .catch( err => next(err)); +// }); app.listen(PORT, () => { diff --git a/lab-jinho/test/restaurant-route-test.js b/lab-jinho/test/restaurant-route-test.js index 37c4e7d..80059f1 100644 --- a/lab-jinho/test/restaurant-route-test.js +++ b/lab-jinho/test/restaurant-route-test.js @@ -2,11 +2,17 @@ const request = require('superagent'); const expect = require('chai').expect; +const Restaurant = require('../model/restaurant.js'); +const url = 'http://localhost:3000'; require('../server.js'); +const exampleRestaurant = { + restaurantname: 'red robin', + address: 'seattle, wa' +}; + describe('Restaurant Routes', function() { - var restaurant = null; //POST: test 400 should respond with 'bad request' if no request body was provided or body was invalid describe('POST: /api/restaurant', function(){ From 5fdb08396c8001892c49e8a869c23b4fbe2319eb Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Tue, 20 Dec 2016 15:28:28 -0800 Subject: [PATCH 36/49] delete corpse code --- lab-jinho/server.js | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/lab-jinho/server.js b/lab-jinho/server.js index f9617d2..6ef3d1c 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -27,17 +27,6 @@ app.use(cors); app.use(errors); app.use(restaurantRouter); - - -// app.delete('/api/restaurant', function(req, res, next) { -// debug('DELETE: /api/restaurant'); -// -// Restaurant.deleteRestaurant('restaurant', req.query.id) -// .then( () => res.status(204).send()) -// .catch( err => next(err)); -// }); - - app.listen(PORT, () => { console.log(`server up: ${PORT}`); }); From 1dd273dc31e73b07453ec6d7f0a32f23323c41b3 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Wed, 21 Dec 2016 10:23:53 -0800 Subject: [PATCH 37/49] added test and debug files with linter errors --- lab-jinho/lib/storage.js | 5 +- lab-jinho/server.js | 2 +- lab-jinho/test/restaurant-route-test.js | 139 +++++++++++++++--------- 3 files changed, 91 insertions(+), 55 deletions(-) diff --git a/lab-jinho/lib/storage.js b/lab-jinho/lib/storage.js index b13130f..952e6fd 100644 --- a/lab-jinho/lib/storage.js +++ b/lab-jinho/lib/storage.js @@ -5,9 +5,6 @@ const fs = Promise.promisifyAll(require('fs'), {suffix: 'Prom'}); const createError = require('http-errors'); const debug = require('debug')('restaurant:storage'); -const storage = {}; - - module.exports = exports = {}; exports.createItem = function(schemaName, item) { @@ -52,6 +49,6 @@ exports.deleteItem = function(schemaName, id){ exports.availIDs = function(schemaName) { return fs.readdirProm(`${__dirname}/../data/${schemaName}`) - .then( files => files.map(name => name.split('.json')[0])) + .then( files => files.map(restaurantname => restaurantname.split('.json')[0])) .catch( err => Promise.reject(createError(404, err.message))); }; diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 6ef3d1c..48856fe 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -8,7 +8,7 @@ const createError = require('http-errors'); const debug = require('debug')('restaurant:server'); const cors = require('./lib/cors-middleware.js'); const errors = require('./lib/error-middleware.js'); -const restaurantRouter = require('./route/restaurantRouter.js'); +const restaurantRouter = require('./route/restaurant-router.js'); //npm modules //custom modules diff --git a/lab-jinho/test/restaurant-route-test.js b/lab-jinho/test/restaurant-route-test.js index 80059f1..06e1bf7 100644 --- a/lab-jinho/test/restaurant-route-test.js +++ b/lab-jinho/test/restaurant-route-test.js @@ -14,65 +14,104 @@ const exampleRestaurant = { describe('Restaurant Routes', function() { -//POST: test 400 should respond with 'bad request' if no request body was provided or body was invalid - describe('POST: /api/restaurant', function(){ - it('respond with bad request - POST', function(done){ - request.post('localhost:3000/api/restaurant') - .send({invalid:'invalid body'}) - .end((err, res) => { - expect(res.status).to.equal(400); - expect(res.text).to.equal('BadRequestError'); - done(); + describe('GET: /api/restaurant', function() { + describe('with a valid id', function() { + before( done => { + Restaurant.createRestaurant(exampleRestaurant) + .then(restaurant => { + this.tempRestaurant = restaurant; + done(); + }) + .catch( err => done(err)); + }); + + after( done => { + Restaurant.deleteRestaurant(this.tempRestaurant.id) + .then( ()=> done()) + .catch( err => done(err)); + }); + + it('should return restaurant', done => { + request.get(`${url}/api/restaurant/${this.tempRestaurant.id}`) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.id).to.equal(this.tempRestaurant.id); + expect(res.body.restaurantname).to.equal(this.tempRestaurant.restaurantname); + expect(res.body.address).to.equal(this.tempRestaurant.address); + done(); + }); + }); + + describe('with invalid id', function() { + it('should respond with 404 status code', done => { + request.get(`${url}/api/restaurant/123`) + .end((err, res) => { + expect(res.status).to.equal(404); + done(); + }); + }); }); }); }); -//POST: test 200 should respond with the body content for post request with valid body + describe('POST: /api/restaurant', function() { - it('should return a restaurant', function(done) { - request.post('localhost:3000/api/restaurant') - .send({restaurantname: 'test restaurant name', address: 'test address'}) - .end((err, res) => { - if (err) return done(err); - expect(res.status).to.equal(200); - expect(res.body.restaurantname).to.equal('test restaurant name'); - expect(res.body.address).to.equal('test address'); - restaurant = res.body; - done(); + describe('with valid body', function() { + after( done => { + if (this.tempRestaurant) { + Restaurant.deleteRestaurant(this.tempRestaurant.id) + .then( ()=> done()) + .catch( err => done(err)); + } }); - }); - }); -//GET: test 404 should respond with 'not found' for valid requests made with id not found - describe('GET: /api/restaurant', function(){ - it('return error for no id valid request - GET', function(done){ - request.get('localhost:3000/api/restaurant?id=123') - .end((err, res) => { - expect(res.status).to.equal(404); - expect(res.text).to.equal('NotFoundError'); - done(); + + it('should return restaurant', done => { + request.post(`${url}/api/restaurant`) + .send(exampleRestaurant) + .end((err, res) => { + if (err) return done (err); + expect(res.status).to.equal(200); + expect(res.body.restaurantname).to.equal(exampleRestaurant.restaurantname); + expect(res.body.address).to.equal(exampleRestaurant.address); + this.tempRestaurant = res.body; + done(); + }); }); }); }); -//GET: test 400 should respond with 'bad request' if no id was provided in request - describe('GET: /api/restaurant', function(){ - it('return error with no id - GET', function(done){ - request.get('localhost:3000/api/restaurant') - .end((err, res) => { - expect(res.status).to.equal(400); - expect(res.text).to.equal('BadRequestError'); - done(); + + describe('PUT: /api/restaurant', function() { + describe('with valid id and body', function() { + before( done => { + Restaurant.createRestaurant(exampleRestaurant) + .then( restaurant => { + this.tempRestaurant = restaurant; + done(); + }) + .catch( err => done(err)); }); - }); - }); -//GET: test 200 should contain response body for request made with valid id - describe('GET: /api/restaurant', function() { - it('should return a restaurant', function(done) { - request.get(`localhost:3000/api/restaurant?id=${restaurant.id}`) - .end((err, res) => { - if (err) return done(err); - expect(res.status).to.equal(200); - expect(res.body.restaurantname).to.equal('test restaurant name'); - expect(res.body.address).to.equal('test address'); - done(); + + after( done => { + if (this.tempRestaurant) { + Restaurant.deleteRestaurant(this.tempRestaurant.id) + .then( ()=> done()) + .catch(done); + } + }); + + it('should return restaurant', done => { + let updateRestaurant = { restaurantname: 'new restaurant name', address: 'new address'}; + request.put(`${url}/api/restaurant?id=${this.tempRestaurant.id}`) + .send(updateRestaurant) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.id).to.equal(this.tempRestaurant.id); + for (var prop in updateRestaurant) { + expect(res.body[prop]).to.equal(updateRestaurant[prop]); + } + done(); + }); }); }); }); From d2c35ad40d429d7e4534af6d8a678e4d47f6cb1e Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Wed, 21 Dec 2016 10:30:54 -0800 Subject: [PATCH 38/49] debugging tests --- lab-jinho/model/restaurant.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lab-jinho/model/restaurant.js b/lab-jinho/model/restaurant.js index 104bee3..4b4463a 100644 --- a/lab-jinho/model/restaurant.js +++ b/lab-jinho/model/restaurant.js @@ -46,7 +46,7 @@ Restaurant.updateRestaurant = function(id, _restaurant) { }); }; -Restaurant.deleteRestaurant = function(schemaName, id) { +Restaurant.deleteRestaurant = function(id) { debug('deleteRestaurant'); return storage.deleteItem('restaurant', id); }; From e5ac62642b061e47eba326b248e3591879251814 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Wed, 21 Dec 2016 13:52:34 -0800 Subject: [PATCH 39/49] setup server for mongo demo --- lab-jinho/lib/cors-middleware.js | 7 ---- lab-jinho/lib/error-middleware.js | 21 ------------ lab-jinho/lib/storage.js | 54 ------------------------------- lab-jinho/package.json | 6 ++-- lab-jinho/server.js | 19 +++++------ 5 files changed, 12 insertions(+), 95 deletions(-) delete mode 100644 lab-jinho/lib/cors-middleware.js delete mode 100644 lab-jinho/lib/error-middleware.js delete mode 100644 lab-jinho/lib/storage.js diff --git a/lab-jinho/lib/cors-middleware.js b/lab-jinho/lib/cors-middleware.js deleted file mode 100644 index 6661797..0000000 --- a/lab-jinho/lib/cors-middleware.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -module.exports = function(req, res, next) { - res.append('Access-Control-Allow-Origin', '*'); - res.append('Access-Control-Allow-Headers', '*'); - next(); -}; diff --git a/lab-jinho/lib/error-middleware.js b/lab-jinho/lib/error-middleware.js deleted file mode 100644 index 96a627a..0000000 --- a/lab-jinho/lib/error-middleware.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -const createError = require('http-errors'); -const debug = require('debug')('restaurant:error-middleware'); - -module.exports = function(err, req, res, next) { - console.error(err.message); - - if (err.status) { - debug('user error'); - - res.status(err.status).send(err.name); - next(); - return; - } - - debug('server error'); - err = createError(500, err.message); - res.status(err.status).send(err.name); - next(); -}; diff --git a/lab-jinho/lib/storage.js b/lab-jinho/lib/storage.js deleted file mode 100644 index 952e6fd..0000000 --- a/lab-jinho/lib/storage.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -const Promise = require('bluebird'); -const fs = Promise.promisifyAll(require('fs'), {suffix: 'Prom'}); -const createError = require('http-errors'); -const debug = require('debug')('restaurant:storage'); - -module.exports = exports = {}; - -exports.createItem = function(schemaName, item) { - debug('createItem'); - - if (!schemaName) return Promise.reject(createError(400, 'expected schemaName')); - if (!item) return Promise.reject(createError(400, 'expected item')); - - let json = JSON.stringify(item); - return fs.writeFileProm(`${__dirname}/../data/${schemaName}/${item.id}.json`, json) - .then( () => item) - .catch( err => Promise.reject(createError(500, err.message))); -}; - -exports.fetchItem = function(schemaName, id) { - debug('fetchItem'); - - if (!schemaName) return Promise.reject(createError(400, 'expected schema name')); - if (!id) return Promise.reject(createError(400, 'expected id')); - - return fs.readFileProm(`${__dirname}/../data/${schemaName}/${id}.json`) - .then(data => { - try { - let item = JSON.parse(data.toString()); - return item; - } catch (err) { - return Promise.reject(createError(500, err.message)); - } - }) - .catch(err => Promise.reject(createError(404, err.message))); -}; - -exports.deleteItem = function(schemaName, id){ - debug('deleteItem'); - - if (!schemaName) return Promise.reject(createError(400, 'expected schema name')); - if (!id) return Promise.reject(createError(400, 'expected id')); - - return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`) - .catch( err => Promise.reject(createError(404, err.message))); -}; - -exports.availIDs = function(schemaName) { - return fs.readdirProm(`${__dirname}/../data/${schemaName}`) - .then( files => files.map(restaurantname => restaurantname.split('.json')[0])) - .catch( err => Promise.reject(createError(404, err.message))); -}; diff --git a/lab-jinho/package.json b/lab-jinho/package.json index 0bd6c38..b9f8fbe 100644 --- a/lab-jinho/package.json +++ b/lab-jinho/package.json @@ -7,8 +7,8 @@ "test": "test" }, "scripts": { - "test": "DEBUG='restaurant*' mocha", - "start": "DEBUG='restaurant*' node server.js" + "test": "DEBUG='restaurantlist*' mocha", + "start": "DEBUG='restaurantlist*' node server.js" }, "keywords": [], "author": "", @@ -17,9 +17,11 @@ "Express": "^3.0.1", "bluebird": "^3.4.6", "body-parser": "^1.15.2", + "cors": "^2.8.1", "debug": "^2.4.5", "express": "^4.14.0", "http-errors": "^1.5.1", + "mongoose": "^4.7.4", "morgan": "^1.7.0", "node-uuid": "^1.4.7" }, diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 48856fe..d3d65c9 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -4,29 +4,26 @@ //node modules const express = require('express'); const morgan = require('morgan'); -const createError = require('http-errors'); -const debug = require('debug')('restaurant:server'); -const cors = require('./lib/cors-middleware.js'); -const errors = require('./lib/error-middleware.js'); -const restaurantRouter = require('./route/restaurant-router.js'); +const cors = require('cors'); +const Promise = require('bluebird'); +const mongoose = require('mongoose'); +const debug = require('debug')('restaurantlist:server'); + + //npm modules //custom modules //environment variables -const PORT = process.env.PORT || 3000; const app = express(); +const PORT = process.env.PORT || 3000; //module constants //**START SERVER** -app.use(morgan('dev')); -app.use(cors); -app.use(errors); -app.use(restaurantRouter); app.listen(PORT, () => { - console.log(`server up: ${PORT}`); + debug(`server up: ${PORT}`); }); From 00318ab5cb3d76daef28ccaa19585b776c24aa6d Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Wed, 21 Dec 2016 15:45:39 -0800 Subject: [PATCH 40/49] beginning code for mongodb refactor --- lab-jinho/model/restaurant.js | 57 ----------- lab-jinho/model/restaurantlist.js | 66 ++++++++++++ lab-jinho/route/restaurant-router.js | 43 -------- lab-jinho/route/restaurantlist-router.js | 52 ++++++++++ lab-jinho/server.js | 10 +- lab-jinho/test/restaurant-route-test.js | 125 +++++------------------ 6 files changed, 151 insertions(+), 202 deletions(-) delete mode 100644 lab-jinho/model/restaurant.js create mode 100644 lab-jinho/model/restaurantlist.js delete mode 100644 lab-jinho/route/restaurant-router.js create mode 100644 lab-jinho/route/restaurantlist-router.js diff --git a/lab-jinho/model/restaurant.js b/lab-jinho/model/restaurant.js deleted file mode 100644 index 4b4463a..0000000 --- a/lab-jinho/model/restaurant.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; - -const uuid = require('node-uuid'); -const createError = require('http-errors'); -const debug = require('debug')('restaurant:restaurant'); -const storage = require('../lib/storage.js'); - -const Restaurant = module.exports = function(restaurantname, address) { - debug('restaurant constructor'); - - if (!restaurantname) throw createError(400, 'expected restaurant name'); - if (!address) throw createError(400, 'expected address'); - - this.id = uuid.v1(); - this.restaurantname = restaurantname; - this.address = address; -}; - -Restaurant.createRestaurant = function(_restaurant) { - debug('createRestaurant'); - - try { - let restaurant = new Restaurant(_restaurant.restaurantname, _restaurant.address); - return storage.createItem('restaurant', restaurant); - } catch (err) { - return Promise.reject(createError(400, err.message)); - } -}; - -Restaurant.fetchRestaurant = function(id) { - debug('fetchRestaurant'); - return storage.fetchItem('restaurant', id); -}; - -Restaurant.updateRestaurant = function(id, _restaurant) { - debug('updateRestaurant'); - - return storage.fetchItem('restaurant', id) - .catch(err => Promise.reject(createError(404, err.message))) - .then( restaurant => { - for (var prop in restaurant) { - if (prop === 'id') continue; - if (_restaurant[prop]) restaurant[prop] = _restaurant[prop]; - } - return storage.createItem('restaurant', restaurant); - }); -}; - -Restaurant.deleteRestaurant = function(id) { - debug('deleteRestaurant'); - return storage.deleteItem('restaurant', id); -}; - -Restaurant.fetchIDs = function() { - debug('fetchIDs'); - return storage.availIDs('restaurant'); -}; diff --git a/lab-jinho/model/restaurantlist.js b/lab-jinho/model/restaurantlist.js new file mode 100644 index 0000000..61dce52 --- /dev/null +++ b/lab-jinho/model/restaurantlist.js @@ -0,0 +1,66 @@ +'use strict'; + +const mongoose = require('mongoose'); +const Schema = mongoose.Schema; + +const restaurantlistSchema = Schema({ + restaurantname: { type: String, required: true } + timestamp: { type: Date, required: true } + address: { type: String, required: true } +}); + +// const uuid = require('node-uuid'); +// const createError = require('http-errors'); +// const debug = require('debug')('restaurant:restaurant'); +// const storage = require('../lib/storage.js'); + +module.exports = mongoose.model('restaurantlist', restaurantlistSchema ) { +// debug('restaurant constructor'); +// +// if (!restaurantname) throw createError(400, 'expected restaurant name'); +// if (!address) throw createError(400, 'expected address'); +// +// this.id = uuid.v1(); +// this.restaurantname = restaurantname; +// this.address = address; +// }; +// +// Restaurant.createRestaurant = function(_restaurant) { +// debug('createRestaurant'); +// +// try { +// let restaurant = new Restaurant(_restaurant.restaurantname, _restaurant.address); +// return storage.createItem('restaurant', restaurant); +// } catch (err) { +// return Promise.reject(createError(400, err.message)); +// } +// }; +// +// Restaurant.fetchRestaurant = function(id) { +// debug('fetchRestaurant'); +// return storage.fetchItem('restaurant', id); +// }; +// +// Restaurant.updateRestaurant = function(id, _restaurant) { +// debug('updateRestaurant'); +// +// return storage.fetchItem('restaurant', id) +// .catch(err => Promise.reject(createError(404, err.message))) +// .then( restaurant => { +// for (var prop in restaurant) { +// if (prop === 'id') continue; +// if (_restaurant[prop]) restaurant[prop] = _restaurant[prop]; +// } +// return storage.createItem('restaurant', restaurant); +// }); +// }; +// +// Restaurant.deleteRestaurant = function(id) { +// debug('deleteRestaurant'); +// return storage.deleteItem('restaurant', id); +// }; +// +// Restaurant.fetchIDs = function() { +// debug('fetchIDs'); +// return storage.availIDs('restaurant'); +// }; diff --git a/lab-jinho/route/restaurant-router.js b/lab-jinho/route/restaurant-router.js deleted file mode 100644 index c8449d2..0000000 --- a/lab-jinho/route/restaurant-router.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -const Router = require('express').Router; -const jsonParser = require('body-parser').json(); -const debug = require('debug')('restaurant:restaurant-router'); -const Restaurant = require('../model/restaurant.js'); -const restaurantRouter = new Router(); - -restaurantRouter.post('/api/restaurant', jsonParser, function(req, res, next) { - debug('POST: /api/restaurant'); - - Restaurant.createRestaurant(req.body) - .then( restaurant => res.json(restaurant)) - .catch( err => next(err)); -}); - -restaurantRouter.get('/api/restaurant/:id', function(req, res, next) { - debug('GET: /api/restaurant/:id'); - - Restaurant.fetchRestaurant(req.params.id) - .then( restaurant => res.json(restaurant)) - .catch( err => next(err)); -}); - -restaurantRouter.get('/api/restaurant', function(req, res, next) { - debug('GET: /api/restaurant'); - - Restaurant.fetchIDs() - .then( ids => res.json(ids)) - .catch(next); -}); - -restaurantRouter.put('/api/restaurant', jsonParser, function(req, res, next) { - debug('PUT: /api/restaurant'); - - Restaurant.updateRestaurant(req.query.id, req.body) - .then( restaurant => res.json(restaurant)) - .catch(next); -}); - - - -module.exports = restaurantRouter; diff --git a/lab-jinho/route/restaurantlist-router.js b/lab-jinho/route/restaurantlist-router.js new file mode 100644 index 0000000..7c92096 --- /dev/null +++ b/lab-jinho/route/restaurantlist-router.js @@ -0,0 +1,52 @@ +'use strict'; + +const Router = require('express').Router; +const jsonParser = require('body-parser').json(); +const Restaurantlist = require('../model/restaurantlist.js'); +const debug = require('debug')('restaurantlist:restaurantlist-router'); +const restaurantlistRouter = module.exports = new Router(); + + + +restaurantlistRouter.post('/api/restaurantlist', jsonParser, function(req, res, next) { + debug('POST: /api/restaurantlist'); + + req.body.timestamp = new Date(); + new Restaurantlist(req.body).save() + .then( restaurantlist => res.json(restaurantlist)) + .catch(next); +}); + + // Restaurant.createRestaurant(req.body) + // .then( restaurant => res.json(restaurant)) + // .catch( err => next(err)); + +restaurantlistRouter.get('/api/restaurantlist/:id', function(req, res, next) { + debug('GET: /api/restaurantlist/:id'); + + Restaurantlist.findById(req.params.id) + .then( restaurantlist => res.json(restaurantlist)) + .catch(next); +}); + + + +restaurantRouter.get('/api/restaurant', function(req, res, next) { + debug('GET: /api/restaurant'); + + Restaurant.fetchIDs() + .then( ids => res.json(ids)) + .catch(next); +}); + +restaurantRouter.put('/api/restaurant', jsonParser, function(req, res, next) { + debug('PUT: /api/restaurant'); + + Restaurant.updateRestaurant(req.query.id, req.body) + .then( restaurant => res.json(restaurant)) + .catch(next); +}); + + + +module.exports = restaurantRouter; diff --git a/lab-jinho/server.js b/lab-jinho/server.js index d3d65c9..064a895 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -7,6 +7,7 @@ const morgan = require('morgan'); const cors = require('cors'); const Promise = require('bluebird'); const mongoose = require('mongoose'); +const restaurantlistRouter = require('./route/restaurantlist-router.js'); const debug = require('debug')('restaurantlist:server'); @@ -18,8 +19,15 @@ const debug = require('debug')('restaurantlist:server'); //environment variables const app = express(); const PORT = process.env.PORT || 3000; -//module constants +const MONGODB_URI = 'mongodb://localhost/restaurantlist'; + +mongoose.Promise = Promise; +mongoose.connect(MONGODB_URI); +//module constants +app.use(cors()); +app.use(morgan('dev')); +app.use(restaurantlistRouter); //**START SERVER** diff --git a/lab-jinho/test/restaurant-route-test.js b/lab-jinho/test/restaurant-route-test.js index 06e1bf7..25bfeb3 100644 --- a/lab-jinho/test/restaurant-route-test.js +++ b/lab-jinho/test/restaurant-route-test.js @@ -2,116 +2,39 @@ const request = require('superagent'); const expect = require('chai').expect; -const Restaurant = require('../model/restaurant.js'); -const url = 'http://localhost:3000'; +const Restaurantlist = require('../model/restaurantlist.js'); +const PORT = process.env.PORT || 3000; +// const MONGODB_URI = 'mongodb://localhost/restaurantlist'; require('../server.js'); -const exampleRestaurant = { +const url = `http://localhost:${PORT}`; + +const exampleRestaurantlist = { restaurantname: 'red robin', - address: 'seattle, wa' }; -describe('Restaurant Routes', function() { - - describe('GET: /api/restaurant', function() { - describe('with a valid id', function() { - before( done => { - Restaurant.createRestaurant(exampleRestaurant) - .then(restaurant => { - this.tempRestaurant = restaurant; - done(); - }) - .catch( err => done(err)); - }); - - after( done => { - Restaurant.deleteRestaurant(this.tempRestaurant.id) +describe('POST: /api/restaurantlist', function() { + describe('with valid body', function() { + after( done => { + if (this.tempRestaurantlist) { + Restaurantlist.remove({}) .then( ()=> done()) - .catch( err => done(err)); - }); - - it('should return restaurant', done => { - request.get(`${url}/api/restaurant/${this.tempRestaurant.id}`) - .end((err, res) => { - if (err) return done(err); - expect(res.status).to.equal(200); - expect(res.body.id).to.equal(this.tempRestaurant.id); - expect(res.body.restaurantname).to.equal(this.tempRestaurant.restaurantname); - expect(res.body.address).to.equal(this.tempRestaurant.address); - done(); - }); - }); - - describe('with invalid id', function() { - it('should respond with 404 status code', done => { - request.get(`${url}/api/restaurant/123`) - .end((err, res) => { - expect(res.status).to.equal(404); - done(); - }); - }); - }); - }); - }); - - describe('POST: /api/restaurant', function() { - describe('with valid body', function() { - after( done => { - if (this.tempRestaurant) { - Restaurant.deleteRestaurant(this.tempRestaurant.id) - .then( ()=> done()) - .catch( err => done(err)); - } - }); - - it('should return restaurant', done => { - request.post(`${url}/api/restaurant`) - .send(exampleRestaurant) - .end((err, res) => { - if (err) return done (err); - expect(res.status).to.equal(200); - expect(res.body.restaurantname).to.equal(exampleRestaurant.restaurantname); - expect(res.body.address).to.equal(exampleRestaurant.address); - this.tempRestaurant = res.body; - done(); - }); - }); + .catch(done); + return; + } + done(); }); - }); - - describe('PUT: /api/restaurant', function() { - describe('with valid id and body', function() { - before( done => { - Restaurant.createRestaurant(exampleRestaurant) - .then( restaurant => { - this.tempRestaurant = restaurant; - done(); - }) - .catch( err => done(err)); - }); - - after( done => { - if (this.tempRestaurant) { - Restaurant.deleteRestaurant(this.tempRestaurant.id) - .then( ()=> done()) - .catch(done); - } - }); - it('should return restaurant', done => { - let updateRestaurant = { restaurantname: 'new restaurant name', address: 'new address'}; - request.put(`${url}/api/restaurant?id=${this.tempRestaurant.id}`) - .send(updateRestaurant) - .end((err, res) => { - if (err) return done(err); - expect(res.status).to.equal(200); - expect(res.body.id).to.equal(this.tempRestaurant.id); - for (var prop in updateRestaurant) { - expect(res.body[prop]).to.equal(updateRestaurant[prop]); - } - done(); - }); + it('should return restaurantlist', done => { + request.put(`${url}/api/restaurantlist`) + .send(exampleRestaurantlist) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.restaurantname).to.equal('red robin'); + this.tempRestaurantlist = res.body; + done(); }); }); }); From ebadc8fd950468bcc72d1edb4d66ac902862dd2a Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Wed, 21 Dec 2016 19:28:39 -0800 Subject: [PATCH 41/49] debug and writing more tests --- lab-jinho/model/restaurantlist.js | 59 +----------------------- lab-jinho/route/restaurantlist-route.js | 21 +++++++++ lab-jinho/route/restaurantlist-router.js | 52 --------------------- lab-jinho/server.js | 14 ++---- 4 files changed, 26 insertions(+), 120 deletions(-) create mode 100644 lab-jinho/route/restaurantlist-route.js delete mode 100644 lab-jinho/route/restaurantlist-router.js diff --git a/lab-jinho/model/restaurantlist.js b/lab-jinho/model/restaurantlist.js index 61dce52..a038a60 100644 --- a/lab-jinho/model/restaurantlist.js +++ b/lab-jinho/model/restaurantlist.js @@ -4,63 +4,8 @@ const mongoose = require('mongoose'); const Schema = mongoose.Schema; const restaurantlistSchema = Schema({ - restaurantname: { type: String, required: true } + restaurantname: { type: String, required: true }, timestamp: { type: Date, required: true } - address: { type: String, required: true } }); -// const uuid = require('node-uuid'); -// const createError = require('http-errors'); -// const debug = require('debug')('restaurant:restaurant'); -// const storage = require('../lib/storage.js'); - -module.exports = mongoose.model('restaurantlist', restaurantlistSchema ) { -// debug('restaurant constructor'); -// -// if (!restaurantname) throw createError(400, 'expected restaurant name'); -// if (!address) throw createError(400, 'expected address'); -// -// this.id = uuid.v1(); -// this.restaurantname = restaurantname; -// this.address = address; -// }; -// -// Restaurant.createRestaurant = function(_restaurant) { -// debug('createRestaurant'); -// -// try { -// let restaurant = new Restaurant(_restaurant.restaurantname, _restaurant.address); -// return storage.createItem('restaurant', restaurant); -// } catch (err) { -// return Promise.reject(createError(400, err.message)); -// } -// }; -// -// Restaurant.fetchRestaurant = function(id) { -// debug('fetchRestaurant'); -// return storage.fetchItem('restaurant', id); -// }; -// -// Restaurant.updateRestaurant = function(id, _restaurant) { -// debug('updateRestaurant'); -// -// return storage.fetchItem('restaurant', id) -// .catch(err => Promise.reject(createError(404, err.message))) -// .then( restaurant => { -// for (var prop in restaurant) { -// if (prop === 'id') continue; -// if (_restaurant[prop]) restaurant[prop] = _restaurant[prop]; -// } -// return storage.createItem('restaurant', restaurant); -// }); -// }; -// -// Restaurant.deleteRestaurant = function(id) { -// debug('deleteRestaurant'); -// return storage.deleteItem('restaurant', id); -// }; -// -// Restaurant.fetchIDs = function() { -// debug('fetchIDs'); -// return storage.availIDs('restaurant'); -// }; +module.exports = mongoose.model('restaurantlist', restaurantlistSchema); diff --git a/lab-jinho/route/restaurantlist-route.js b/lab-jinho/route/restaurantlist-route.js new file mode 100644 index 0000000..65b7760 --- /dev/null +++ b/lab-jinho/route/restaurantlist-route.js @@ -0,0 +1,21 @@ +'use strict'; + +const Router = require('express').Router; +const jsonParser = require('body-parser').json(); +const Restaurantlist = require('../model/restaurantlist.js'); +const restaurantlistRouter = module.exports = new Router(); + + + +restaurantlistRouter.post('/api/restaurantlist', jsonParser, function(req, res, next) { + req.body.timestamp = new Date(); + new Restaurantlist(req.body).save() + .then(restaurantlist => res.json(restaurantlist)) + .catch(next); +}); + +restaurantlistRouter.get('/api/restaurantlist/:id', function(req, res, next) { + Restaurantlist.findById(req.params.id) + .then(restaurantlist => res.json(restaurantlist)) + .catch(next); +}); diff --git a/lab-jinho/route/restaurantlist-router.js b/lab-jinho/route/restaurantlist-router.js deleted file mode 100644 index 7c92096..0000000 --- a/lab-jinho/route/restaurantlist-router.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -const Router = require('express').Router; -const jsonParser = require('body-parser').json(); -const Restaurantlist = require('../model/restaurantlist.js'); -const debug = require('debug')('restaurantlist:restaurantlist-router'); -const restaurantlistRouter = module.exports = new Router(); - - - -restaurantlistRouter.post('/api/restaurantlist', jsonParser, function(req, res, next) { - debug('POST: /api/restaurantlist'); - - req.body.timestamp = new Date(); - new Restaurantlist(req.body).save() - .then( restaurantlist => res.json(restaurantlist)) - .catch(next); -}); - - // Restaurant.createRestaurant(req.body) - // .then( restaurant => res.json(restaurant)) - // .catch( err => next(err)); - -restaurantlistRouter.get('/api/restaurantlist/:id', function(req, res, next) { - debug('GET: /api/restaurantlist/:id'); - - Restaurantlist.findById(req.params.id) - .then( restaurantlist => res.json(restaurantlist)) - .catch(next); -}); - - - -restaurantRouter.get('/api/restaurant', function(req, res, next) { - debug('GET: /api/restaurant'); - - Restaurant.fetchIDs() - .then( ids => res.json(ids)) - .catch(next); -}); - -restaurantRouter.put('/api/restaurant', jsonParser, function(req, res, next) { - debug('PUT: /api/restaurant'); - - Restaurant.updateRestaurant(req.query.id, req.body) - .then( restaurant => res.json(restaurant)) - .catch(next); -}); - - - -module.exports = restaurantRouter; diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 064a895..61c655b 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -1,37 +1,29 @@ 'use strict'; //**DEPENDENCIES** -//node modules const express = require('express'); const morgan = require('morgan'); const cors = require('cors'); const Promise = require('bluebird'); const mongoose = require('mongoose'); -const restaurantlistRouter = require('./route/restaurantlist-router.js'); const debug = require('debug')('restaurantlist:server'); +const restaurantlistRouter = require('./route/restaurantlist-route.js'); - -//npm modules - -//custom modules - - -//environment variables const app = express(); + const PORT = process.env.PORT || 3000; const MONGODB_URI = 'mongodb://localhost/restaurantlist'; mongoose.Promise = Promise; mongoose.connect(MONGODB_URI); -//module constants +//app.use() app.use(cors()); app.use(morgan('dev')); app.use(restaurantlistRouter); //**START SERVER** - app.listen(PORT, () => { debug(`server up: ${PORT}`); }); From 0425121644ad48479445de4af8e2ae5697b934a7 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Wed, 21 Dec 2016 19:43:26 -0800 Subject: [PATCH 42/49] completed writing tests --- lab-jinho/test/restaurant-route-test.js | 81 ++++++++++++++++++------- 1 file changed, 59 insertions(+), 22 deletions(-) diff --git a/lab-jinho/test/restaurant-route-test.js b/lab-jinho/test/restaurant-route-test.js index 25bfeb3..fea86d0 100644 --- a/lab-jinho/test/restaurant-route-test.js +++ b/lab-jinho/test/restaurant-route-test.js @@ -1,41 +1,78 @@ 'use strict'; -const request = require('superagent'); const expect = require('chai').expect; +const request = require('superagent'); const Restaurantlist = require('../model/restaurantlist.js'); const PORT = process.env.PORT || 3000; -// const MONGODB_URI = 'mongodb://localhost/restaurantlist'; + +process.env.MONGODB_URI = 'mongodb://localhost/restaurantlisttest'; require('../server.js'); const url = `http://localhost:${PORT}`; - const exampleRestaurantlist = { - restaurantname: 'red robin', + restaurantname: 'test restaurant name' }; -describe('POST: /api/restaurantlist', function() { - describe('with valid body', function() { - after( done => { - if (this.tempRestaurantlist) { - Restaurantlist.remove({}) - .then( ()=> done()) - .catch(done); - return; - } - done(); +describe('Restaurantlist Routes', function() { + describe('POST: /api/restaurantlist', function() { + describe('with valid body', function() { + after( done => { + if (this.tempRestaurantlist) { + Restaurantlist.remove({}) + .then( ()=> done()) + .catch(done); + return; + } + done(); + }); + + it('should return restaurantlist', done => { + request.post(`${url}/api/restaurantlist`) + .send(exampleRestaurantlist) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.restaurantname).to.equal('test restaurant name'); + this.tempRestaurantlist = res.body; + done(); + }); + }); }); + }); - it('should return restaurantlist', done => { - request.put(`${url}/api/restaurantlist`) - .send(exampleRestaurantlist) - .end((err, res) => { - if (err) return done(err); - expect(res.status).to.equal(200); - expect(res.body.restaurantname).to.equal('red robin'); - this.tempRestaurantlist = res.body; + describe('GET: /api/list/:id', function() { + describe('with valid body', function() { + before( done => { + exampleRestaurantlist.timestamp = new Date(); + new Restaurantlist(exampleRestaurantlist).save() + .then( list => { + this.tempRestaurantlist = list; + done(); + }) + .catch(done); + }); + + after( done => { + delete exampleRestaurantlist.timestamp; + if(this.tempRestaurantlist) { + Restaurantlist.remove({}) + .then(() => done()) + .catch(done); + return; + } done(); }); + + it('should return restaurantlist', done => { + request.get(`${url}/api/restaurantlist/${this.tempRestaurantlist._id}`) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.restaurantname).to.equal('test restaurant name'); + done(); + }); + }); }); }); }); From ec6199de07a46e2b16046cec71e7e8a5b80c45f6 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 26 Dec 2016 18:18:53 -0800 Subject: [PATCH 43/49] debugging --- lab-jinho/lib/error-middleware.js | 28 ++++++++++++++ lab-jinho/model/list.js | 36 ++++++++++++++++++ lab-jinho/model/restaurant.js | 12 ++++++ lab-jinho/model/restaurantlist.js | 11 ------ lab-jinho/package.json | 4 +- lab-jinho/route/list-route.js | 37 +++++++++++++++++++ lab-jinho/route/restaurant-route.js | 13 +++++++ lab-jinho/route/restaurantlist-route.js | 21 ----------- lab-jinho/server.js | 20 +++++++--- ...urant-route-test.js => list-route-test.js} | 8 ++++ 10 files changed, 151 insertions(+), 39 deletions(-) create mode 100644 lab-jinho/lib/error-middleware.js create mode 100644 lab-jinho/model/list.js create mode 100644 lab-jinho/model/restaurant.js delete mode 100644 lab-jinho/model/restaurantlist.js create mode 100644 lab-jinho/route/list-route.js create mode 100644 lab-jinho/route/restaurant-route.js delete mode 100644 lab-jinho/route/restaurantlist-route.js rename lab-jinho/test/{restaurant-route-test.js => list-route-test.js} (92%) diff --git a/lab-jinho/lib/error-middleware.js b/lab-jinho/lib/error-middleware.js new file mode 100644 index 0000000..534d8d7 --- /dev/null +++ b/lab-jinho/lib/error-middleware.js @@ -0,0 +1,28 @@ +'use strict'; + +const createError = require('http-errors'); +const debug = require('debug')('restaurant:error-middleware'); + +module.exports = function(err, req, res, next) { + debug('error middleware'); + + console.error('msg:', err.message); + console.error('name:', err.name); + + if (err.status) { + res.status(err.status).send(err.name); + next(); + return; + } + + if (err.name === 'ValidationError') { + err = createError(400, err.message); + res.status(err.status).send(err.name); + next(); + return; + } + + err = createError(500, err.message); + res.status(err.status).send(err.name); + next(); +}; diff --git a/lab-jinho/model/list.js b/lab-jinho/model/list.js new file mode 100644 index 0000000..d369a4f --- /dev/null +++ b/lab-jinho/model/list.js @@ -0,0 +1,36 @@ +'use strict'; + +const mongoose = require('mongoose'); +const createError = require('http-errors'); +const debug = require('debug')('restaurant:list'); +const Schema = mongoose.Schema; + +const Restaurant = require('./restaurant.js'); + +const listSchema = Schema({ + restaurantname: { type: String, required: true }, + timestamp: { type: Date, required: true } + restaurants: [{ type: Schema.Types.ObjectId, ref: 'restaurant' }] +}); + +const List = module.exports = mongoose.model('list', listSchema); + +List.findByIdAndAddNote = function(id, restaurant) { + debug('findByIdAndAddNote'); + + return List.findById(id) + .catch( err => Promise.reject(createError(404, err.message))) + .then( list => { + restaurant.listID = list._id; + this.tempList = list + return new Restaurant(restaurant).save(); + }) + .then( restaurant => { + this.tempList.restaurants.push(restaurant._id); + this.tempRestaurant = restaurant; + return this.tempList.save(); + }) + .then ( () => { + return this.tempRestaurant; + }); +}; diff --git a/lab-jinho/model/restaurant.js b/lab-jinho/model/restaurant.js new file mode 100644 index 0000000..3a151eb --- /dev/null +++ b/lab-jinho/model/restaurant.js @@ -0,0 +1,12 @@ +'use strict'; + +const mongoose = require('mongoose'); +const Schema = mongoose.Schema; + +const restaurantSchema = Schema({ + restaurantname: { type: String, required: true }, + address: { type: String, required: true }, + listID: { type: Schema.Types.ObjectId, required: true } +}); + +module.exports = mongoose.model('restaurant', restaurantSchema); diff --git a/lab-jinho/model/restaurantlist.js b/lab-jinho/model/restaurantlist.js deleted file mode 100644 index a038a60..0000000 --- a/lab-jinho/model/restaurantlist.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; - -const restaurantlistSchema = Schema({ - restaurantname: { type: String, required: true }, - timestamp: { type: Date, required: true } -}); - -module.exports = mongoose.model('restaurantlist', restaurantlistSchema); diff --git a/lab-jinho/package.json b/lab-jinho/package.json index b9f8fbe..16ac0ef 100644 --- a/lab-jinho/package.json +++ b/lab-jinho/package.json @@ -7,8 +7,8 @@ "test": "test" }, "scripts": { - "test": "DEBUG='restaurantlist*' mocha", - "start": "DEBUG='restaurantlist*' node server.js" + "test": "DEBUG='restaurant*' mocha", + "start": "DEBUG='restaurant*' node server.js" }, "keywords": [], "author": "", diff --git a/lab-jinho/route/list-route.js b/lab-jinho/route/list-route.js new file mode 100644 index 0000000..db03bce --- /dev/null +++ b/lab-jinho/route/list-route.js @@ -0,0 +1,37 @@ +'use strict'; + +const Router = require('express').Router; +const jsonParser = require('body-parser').json(); +const createError = require('http-errors'); + +const List = require('../model/list.js'); +const listRouter = module.exports = new Router(); + +listRouter.post('/api/list', jsonParser, function(req, res, next) { + req.body.timestamp = new Date(); + new List(req.body).save() + .then( list => res.json(list)) + .catch(next); +}); + +listRouter.get('/api/list/:id', function(req, res, next) { + List.findById(req.params.id) + .populate('restaurants') + .then( list => res.json(list)) + .catch( err => next(createError(404, err.message))); +}); + +listRouter.put('/api/list/:id', jsonParser, function(req, res, next) { + List.findByIdAndUpdate(req.params.id, req.body, { new: true }) + .then( list => res.json(list)) + .catch( err => { + if (err.name === 'ValidationError') return next(err); + next(createError(404, err.message)); + }); +}); + +listRouter.delete('/api/list/:id', function(req, res, next) { + List.findByIdAndRemove(req.params.id) + .then( () => res.status(204).send()) + .catch( err => next(createError(404, err.message))); +}); diff --git a/lab-jinho/route/restaurant-route.js b/lab-jinho/route/restaurant-route.js new file mode 100644 index 0000000..ced7ccc --- /dev/null +++ b/lab-jinho/route/restaurant-route.js @@ -0,0 +1,13 @@ +'use strict'; + +const Router = require('express').Router; +const jsonParser = require('body-parser').json(); +const List = require('../model/list.js'); + +const restaurantRouter = module.exports = new Router(); + +restaurantRouter.post('/api/list/:listID/restaurant', jsonParser, function(req, res, next) { + List.findByIdAndAddNote(req.params.listID, req.body) + .then( note => res.json(note)) + .catch(next); +}); diff --git a/lab-jinho/route/restaurantlist-route.js b/lab-jinho/route/restaurantlist-route.js deleted file mode 100644 index 65b7760..0000000 --- a/lab-jinho/route/restaurantlist-route.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -const Router = require('express').Router; -const jsonParser = require('body-parser').json(); -const Restaurantlist = require('../model/restaurantlist.js'); -const restaurantlistRouter = module.exports = new Router(); - - - -restaurantlistRouter.post('/api/restaurantlist', jsonParser, function(req, res, next) { - req.body.timestamp = new Date(); - new Restaurantlist(req.body).save() - .then(restaurantlist => res.json(restaurantlist)) - .catch(next); -}); - -restaurantlistRouter.get('/api/restaurantlist/:id', function(req, res, next) { - Restaurantlist.findById(req.params.id) - .then(restaurantlist => res.json(restaurantlist)) - .catch(next); -}); diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 61c655b..98d9d05 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -1,26 +1,36 @@ 'use strict'; //**DEPENDENCIES** + +//npm modules const express = require('express'); const morgan = require('morgan'); +const mongoose = require('mongoose'); const cors = require('cors'); const Promise = require('bluebird'); -const mongoose = require('mongoose'); const debug = require('debug')('restaurantlist:server'); -const restaurantlistRouter = require('./route/restaurantlist-route.js'); -const app = express(); +//app modules +const restaurantlistRouter = require('./route/restaurantlist-route.js'); +const restaurantRouter = require('./'); +const errors = require('./'); +//environment variables const PORT = process.env.PORT || 3000; -const MONGODB_URI = 'mongodb://localhost/restaurantlist'; +const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost/restaurant'; +//**LOGIC** mongoose.Promise = Promise; mongoose.connect(MONGODB_URI); -//app.use() +//middleware components app.use +const app = express(); app.use(cors()); app.use(morgan('dev')); + app.use(restaurantlistRouter); +app.use(restaurantRouter); +app.use(errors); //**START SERVER** diff --git a/lab-jinho/test/restaurant-route-test.js b/lab-jinho/test/list-route-test.js similarity index 92% rename from lab-jinho/test/restaurant-route-test.js rename to lab-jinho/test/list-route-test.js index fea86d0..5966f69 100644 --- a/lab-jinho/test/restaurant-route-test.js +++ b/lab-jinho/test/list-route-test.js @@ -3,6 +3,8 @@ const expect = require('chai').expect; const request = require('superagent'); const Restaurantlist = require('../model/restaurantlist.js'); +const Restaurant = require('../model/restaurant.js'); + const PORT = process.env.PORT || 3000; process.env.MONGODB_URI = 'mongodb://localhost/restaurantlisttest'; @@ -11,7 +13,13 @@ require('../server.js'); const url = `http://localhost:${PORT}`; const exampleRestaurantlist = { + restaurantname: 'test name' + timestamp: new Date() +}; + +const exampleRestaurant = { restaurantname: 'test restaurant name' + timestamp: new Date() }; describe('Restaurantlist Routes', function() { From d2349af32be4a709e54c9caf1d2656e69e694068 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 26 Dec 2016 18:23:36 -0800 Subject: [PATCH 44/49] debugged list model --- lab-jinho/model/list.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lab-jinho/model/list.js b/lab-jinho/model/list.js index d369a4f..d1ca7ef 100644 --- a/lab-jinho/model/list.js +++ b/lab-jinho/model/list.js @@ -9,7 +9,7 @@ const Restaurant = require('./restaurant.js'); const listSchema = Schema({ restaurantname: { type: String, required: true }, - timestamp: { type: Date, required: true } + timestamp: { type: Date, required: true }, restaurants: [{ type: Schema.Types.ObjectId, ref: 'restaurant' }] }); @@ -22,7 +22,7 @@ List.findByIdAndAddNote = function(id, restaurant) { .catch( err => Promise.reject(createError(404, err.message))) .then( list => { restaurant.listID = list._id; - this.tempList = list + this.tempList = list; return new Restaurant(restaurant).save(); }) .then( restaurant => { From 3df7c93e4ae364208eccee5838d6d61bf0baf176 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 26 Dec 2016 18:27:36 -0800 Subject: [PATCH 45/49] writing more tests --- lab-jinho/test/restaurant-route-test.js | 1 + 1 file changed, 1 insertion(+) create mode 100644 lab-jinho/test/restaurant-route-test.js diff --git a/lab-jinho/test/restaurant-route-test.js b/lab-jinho/test/restaurant-route-test.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/lab-jinho/test/restaurant-route-test.js @@ -0,0 +1 @@ +'use strict'; From c5c3bde8cf1a97fa20742bcb0689dcbf9049193e Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Mon, 26 Dec 2016 18:28:37 -0800 Subject: [PATCH 46/49] ds store remove --- .DS_Store | Bin 6148 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index f5a011f8c0cf181313bceb53685072c954e46a2c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK%Wl&^6upxMYOAWq0;yfj28l(e+?J9`6_ORoqC2D@SWuMObwrFDPh>kpZ3yyj zz#s4_d;y;WXC8@K+KNquM0Kxp=iGUmJMtNO#zRD+J4v>QT14c*H8y+{*O>0te#IKD zr3n-!M?m}3r<8J(Z2yA-dhH}-6j4l1=;Hc~Xh0)URL~h#vp}sxZGz|&aUYB^R(cC# zlA}zW#+izdOTS15@W;Q5AtLgZ`9GR>V@T=`#`nK7;%PZ{bNq@KZEan)mLn zdcN=Z>)!j`P)&PPR87imRJ=2_G#SJ$eyvotjHCEXI+*rb4_~Ofiqd>gTo``*Hq8?? z?W#$hlqS!ss2YN6ChE5~XS1EXy|&!x1oO6>bvi*?KHYsbpL^cMqwVKMC!@3T+2{F} zujcVd;Nvj%z~KVEA-G1IPrV|~RQ>_I3+95s$O^CmtiY`(;5HX;?N+jJ5>|i}xJwG? z{XxPth7N0sX6ryw0(VLQ(LC%OcJWB= zY`yYu`mB}k6Sy`#uC} Aq5uE@ From dadadae9fd91918f3faae0cec04e60785a294a76 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Fri, 30 Dec 2016 11:05:03 -0800 Subject: [PATCH 47/49] debug testing and other files --- lab-jinho/server.js | 10 ++-- lab-jinho/test/list-route-test.js | 93 ++++++++++++++++++++++--------- 2 files changed, 72 insertions(+), 31 deletions(-) diff --git a/lab-jinho/server.js b/lab-jinho/server.js index 98d9d05..4ab9a63 100644 --- a/lab-jinho/server.js +++ b/lab-jinho/server.js @@ -8,12 +8,12 @@ const morgan = require('morgan'); const mongoose = require('mongoose'); const cors = require('cors'); const Promise = require('bluebird'); -const debug = require('debug')('restaurantlist:server'); +const debug = require('debug')('restaurant:server'); //app modules -const restaurantlistRouter = require('./route/restaurantlist-route.js'); -const restaurantRouter = require('./'); -const errors = require('./'); +const listRouter = require('./route/list-route.js'); +const restaurantRouter = require('./route/restaurant-route.js'); +const errors = require('./lib/error-middleware.js'); //environment variables const PORT = process.env.PORT || 3000; @@ -28,7 +28,7 @@ const app = express(); app.use(cors()); app.use(morgan('dev')); -app.use(restaurantlistRouter); +app.use(listRouter); app.use(restaurantRouter); app.use(errors); diff --git a/lab-jinho/test/list-route-test.js b/lab-jinho/test/list-route-test.js index 5966f69..50d56aa 100644 --- a/lab-jinho/test/list-route-test.js +++ b/lab-jinho/test/list-route-test.js @@ -2,32 +2,31 @@ const expect = require('chai').expect; const request = require('superagent'); -const Restaurantlist = require('../model/restaurantlist.js'); +const List = require('../model/list.js'); const Restaurant = require('../model/restaurant.js'); const PORT = process.env.PORT || 3000; -process.env.MONGODB_URI = 'mongodb://localhost/restaurantlisttest'; - require('../server.js'); const url = `http://localhost:${PORT}`; -const exampleRestaurantlist = { - restaurantname: 'test name' + +const exampleList = { + name: 'test list', timestamp: new Date() }; const exampleRestaurant = { - restaurantname: 'test restaurant name' - timestamp: new Date() + restaurantname: 'test restaurant', + address: 'test address' }; -describe('Restaurantlist Routes', function() { - describe('POST: /api/restaurantlist', function() { +describe('List Routes', function() { + describe('POST: /api/list', function() { describe('with valid body', function() { after( done => { - if (this.tempRestaurantlist) { - Restaurantlist.remove({}) + if (this.tempList) { + List.remove({}) .then( ()=> done()) .catch(done); return; @@ -35,14 +34,14 @@ describe('Restaurantlist Routes', function() { done(); }); - it('should return restaurantlist', done => { - request.post(`${url}/api/restaurantlist`) - .send(exampleRestaurantlist) + it('should return list', done => { + request.post(`${url}/api/list`) + .send(exampleList) .end((err, res) => { if (err) return done(err); expect(res.status).to.equal(200); - expect(res.body.restaurantname).to.equal('test restaurant name'); - this.tempRestaurantlist = res.body; + expect(res.body.name).to.equal('test restaurant'); + this.tempList = res.body; done(); }); }); @@ -52,32 +51,74 @@ describe('Restaurantlist Routes', function() { describe('GET: /api/list/:id', function() { describe('with valid body', function() { before( done => { - exampleRestaurantlist.timestamp = new Date(); - new Restaurantlist(exampleRestaurantlist).save() + new List(exampleList).save() .then( list => { - this.tempRestaurantlist = list; + this.tempList = list; + return List.findByIdAndAddRestaurant(list._id, exampleRestaurant); + }) + .then( restaurant => { + this.tempRestaurant = restaurant; done(); }) .catch(done); }); after( done => { - delete exampleRestaurantlist.timestamp; - if(this.tempRestaurantlist) { - Restaurantlist.remove({}) - .then(() => done()) + if (this.tempList) { + List.remove({}) + .then( () => done()) .catch(done); return; } done(); }); - it('should return restaurantlist', done => { - request.get(`${url}/api/restaurantlist/${this.tempRestaurantlist._id}`) + it('should return list', done => { + request.get(`${url}/api/list/${this.tempList._id}`) .end((err, res) => { if (err) return done(err); expect(res.status).to.equal(200); - expect(res.body.restaurantname).to.equal('test restaurant name'); + expect(res.body.name).to.equal('test list'); + expect(res.body.restaurants.length).to.equal(1); + expect(res.body.restaurants[0].restaurantname).to.equal(exampleRestaurant.restaurantname); + done(); + }); + }); + }); + }); + + describe('PUT: /api/list/:id', function() { + describe('with valid body', function() { + before( done => { + new List(exampleList).save() + .then( list => { + this.tempList = list; + done(); + }) + .catch(done); + }); + + after( done => { + if (this.tempList) { + List.remove({}) + .then( () => done ()) + .catch(done); + return; + } + done(); + }); + + it('should return list', done => { + var updated = { name: 'updated name' }; + + request.put(`${url}/api/list/${this.tempList._id}`) + .send(updated) + .end((err, res) => { + if (err) return done (err); + let timestamp = new Date(res.body.timestamp); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal(updated.name); + expect(timestamp.toString()).to.equal(exampleList.timestamp.toString()); done(); }); }); From e932cd57095c98276df1d3aede302bf819b3da92 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Fri, 30 Dec 2016 11:37:18 -0800 Subject: [PATCH 48/49] completed debugging list tests --- lab-jinho/model/list.js | 6 +++--- lab-jinho/test/list-route-test.js | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lab-jinho/model/list.js b/lab-jinho/model/list.js index d1ca7ef..65a8171 100644 --- a/lab-jinho/model/list.js +++ b/lab-jinho/model/list.js @@ -8,15 +8,15 @@ const Schema = mongoose.Schema; const Restaurant = require('./restaurant.js'); const listSchema = Schema({ - restaurantname: { type: String, required: true }, + name: { type: String, required: true }, timestamp: { type: Date, required: true }, restaurants: [{ type: Schema.Types.ObjectId, ref: 'restaurant' }] }); const List = module.exports = mongoose.model('list', listSchema); -List.findByIdAndAddNote = function(id, restaurant) { - debug('findByIdAndAddNote'); +List.findByIdAndAddRestaurant = function(id, restaurant) { + debug('findByIdAndAddRestaurant'); return List.findById(id) .catch( err => Promise.reject(createError(404, err.message))) diff --git a/lab-jinho/test/list-route-test.js b/lab-jinho/test/list-route-test.js index 50d56aa..a786908 100644 --- a/lab-jinho/test/list-route-test.js +++ b/lab-jinho/test/list-route-test.js @@ -40,7 +40,7 @@ describe('List Routes', function() { .end((err, res) => { if (err) return done(err); expect(res.status).to.equal(200); - expect(res.body.name).to.equal('test restaurant'); + expect(res.body.name).to.equal('test list'); this.tempList = res.body; done(); }); From f53e69171d719e14cd3fd8bc78def968639666a1 Mon Sep 17 00:00:00 2001 From: JINHO PAIK Date: Fri, 30 Dec 2016 16:32:36 -0800 Subject: [PATCH 49/49] finished writing test and debugging --- lab-jinho/route/restaurant-route.js | 2 +- lab-jinho/test/restaurant-route-test.js | 56 +++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/lab-jinho/route/restaurant-route.js b/lab-jinho/route/restaurant-route.js index ced7ccc..57ff56a 100644 --- a/lab-jinho/route/restaurant-route.js +++ b/lab-jinho/route/restaurant-route.js @@ -7,7 +7,7 @@ const List = require('../model/list.js'); const restaurantRouter = module.exports = new Router(); restaurantRouter.post('/api/list/:listID/restaurant', jsonParser, function(req, res, next) { - List.findByIdAndAddNote(req.params.listID, req.body) + List.findByIdAndAddRestaurant(req.params.listID, req.body) .then( note => res.json(note)) .catch(next); }); diff --git a/lab-jinho/test/restaurant-route-test.js b/lab-jinho/test/restaurant-route-test.js index ad9a93a..f260011 100644 --- a/lab-jinho/test/restaurant-route-test.js +++ b/lab-jinho/test/restaurant-route-test.js @@ -1 +1,57 @@ 'use strict'; + +const expect = require('chai').expect; +const request = require('superagent'); +const List = require('../model/list.js'); +const Restaurant = require('../model/restaurant.js'); + +const PORT = process.env.PORT || 3000; + +require('../server.js'); + +const url = `http://localhost:${PORT}`; + +const exampleList = { + name: 'test list', + timestamp: new Date() +}; + +const exampleRestaurant = { + restaurantname: 'test restaurant', + address: 'test address' +}; + +describe('Restaurant Routes', function() { + describe('POST: /api/list/:listID/restaurant', function() { + describe('with valid list id and restaurant body', () => { + before( done => { + new List(exampleList).save() + .then( list => { + this.tempList = list; + done(); + }) + .catch(done); + }); + + after( done => { + Promise.all([ + List.remove({}), + Restaurant.remove({}) + ]) + .then(() => done()) + .catch(done); + }); + + it('should return restaurant', done => { + request.post(`${url}/api/list/${this.tempList.id}/restaurant`) + .send(exampleRestaurant) + .end((err, res) => { + if (err) return done(err); + expect(res.body.restaurantname).to.equal(exampleRestaurant.restaurantname); + expect(res.body.listID).to.equal(this.tempList._id.toString()); + done(); + }); + }); + }); + }); +});