From 3ffff0e1520fb4f32f641dce6889e12bfe52cb77 Mon Sep 17 00:00:00 2001 From: Jamesbillard12 Date: Wed, 2 Aug 2017 13:24:30 -0700 Subject: [PATCH 01/12] have basic structure for app --- .eslintignore | 5 ++ .eslintrc | 21 +++++++ .gitignore | 136 +++++++++++++++++++++++++++++++++++++++++ model/brewery.js | 0 package.json | 38 ++++++++++++ route/brewery-route.js | 0 server.js | 1 + test/brewery-test.js | 0 8 files changed, 201 insertions(+) create mode 100644 .eslintignore create mode 100644 .eslintrc create mode 100644 .gitignore create mode 100644 model/brewery.js create mode 100644 package.json create mode 100644 route/brewery-route.js create mode 100644 server.js create mode 100644 test/brewery-test.js diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..05b1cf3 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,5 @@ +**/node_modules/* +**/vendor/* +**/*.min.js +**/coverage/* +**/build/* diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 0000000..8dc6807 --- /dev/null +++ b/.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/.gitignore b/.gitignore new file mode 100644 index 0000000..345130c --- /dev/null +++ b/.gitignore @@ -0,0 +1,136 @@ +# Created by https://www.gitignore.io/api/osx,vim,node,macos,windows + +### macOS ### +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### Node ### +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.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 + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Typescript v1 declaration files +typings/ + +# 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 + +# dotenv environment variables file +.env + + +### OSX ### + +# Icon must end with two \r + +# Thumbnails + +# Files that might appear in the root of a volume + +# Directories potentially created on remote AFP share + +### Vim ### +# swap +[._]*.s[a-v][a-z] +[._]*.sw[a-p] +[._]s[a-v][a-z] +[._]sw[a-p] +# session +Session.vim +# temporary +.netrwhist +*~ +# auto-generated tag files +tags + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# End of https://www.gitignore.io/api/osx,vim,node,macos,windows diff --git a/model/brewery.js b/model/brewery.js new file mode 100644 index 0000000..e69de29 diff --git a/package.json b/package.json new file mode 100644 index 0000000..f0adc86 --- /dev/null +++ b/package.json @@ -0,0 +1,38 @@ +{ + "name": "13-mongodb", + "version": "1.0.0", + "description": "![CF](https://camo.githubusercontent.com/70edab54bba80edb7493cad3135e9606781cbb6b/687474703a2f2f692e696d6775722e636f6d2f377635415363382e706e67) 13: Single Resource Mongo and Express API ===", + "main": "server.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "start": "node server.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Jamesbillard12/13-mongodb.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/Jamesbillard12/13-mongodb/issues" + }, + "homepage": "https://github.com/Jamesbillard12/13-mongodb#readme", + "dependencies": { + "bluebird": "^3.5.0", + "body-parser": "^1.17.2", + "cors": "^2.8.4", + "debug": "^2.6.8", + "express": "^4.15.3", + "mongoose": "^4.11.5", + "morgan": "^1.8.2" + }, + "devDependencies": { + "chai": "^4.1.0", + "mocha": "^3.5.0", + "superagent": "^3.5.2" + } +} diff --git a/route/brewery-route.js b/route/brewery-route.js new file mode 100644 index 0000000..e69de29 diff --git a/server.js b/server.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/server.js @@ -0,0 +1 @@ +'use strict'; diff --git a/test/brewery-test.js b/test/brewery-test.js new file mode 100644 index 0000000..e69de29 From aced9b5d135f6d6be0c776885b17a0a0cbefde83 Mon Sep 17 00:00:00 2001 From: Jamesbillard12 Date: Wed, 2 Aug 2017 13:51:23 -0700 Subject: [PATCH 02/12] finished model --- model/brewery.js | 13 +++++++++++++ package.json | 4 ++-- server.js | 13 +++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/model/brewery.js b/model/brewery.js index e69de29..b323538 100644 --- a/model/brewery.js +++ b/model/brewery.js @@ -0,0 +1,13 @@ +'use strict'; + +const mongoose = require('mongoose'); +const Schema = mongoose.Schema; + +const brewerySchema = Schema ({ + name: {type: String, require: true}, + address: {type: String, require: true}, + phoneNumber: {type: String, require: true}, + timestamp: {type: Date, require: true} +}); + +module.exports = mongoose.model('brewery', brewerySchema); diff --git a/package.json b/package.json index f0adc86..8af7a90 100644 --- a/package.json +++ b/package.json @@ -7,8 +7,8 @@ "test": "test" }, "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", - "start": "node server.js" + "test": "DEBUG='bew*' mocha", + "start": "DEBUG='bew*' node server.js" }, "repository": { "type": "git", diff --git a/server.js b/server.js index ad9a93a..07b30f2 100644 --- a/server.js +++ b/server.js @@ -1 +1,14 @@ 'use strict'; + +const express = require('express'); +const morgan = require('morgan'); +const cors = require('cors'); +const Promise = require('bluebird'); +const debug = require('debug')('bew:server'); + +const app = express(); +const PORT = process.env.PORT || 3000; + +app.listen(PORT, () => { + debug(`listening on ${PORT}`); +}); From 87ce7f58103ce2c1923bb122b6c9ec9977975e0c Mon Sep 17 00:00:00 2001 From: Jamesbillard12 Date: Wed, 2 Aug 2017 14:55:47 -0700 Subject: [PATCH 03/12] finished route and server --- route/brewery-route.js | 39 +++++++++++++++++++++++++++++++++++++++ server.js | 10 ++++++++++ 2 files changed, 49 insertions(+) diff --git a/route/brewery-route.js b/route/brewery-route.js index e69de29..e43a5e5 100644 --- a/route/brewery-route.js +++ b/route/brewery-route.js @@ -0,0 +1,39 @@ +'use strict'; + +const Router = require('express').Router; +const jsonParser = require('body-parser').json(); +const debug = require('debug')('brew:brewery-router'); +const Brewery = require('../model/brewery.js'); +const breweryRouter = module.exports = new Router(); + +breweryRouter.post('/api/brewery', jsonParser, function (req, res, next) { + debug('POST: /api/brewery'); + + req.body.timestamp = new Date(); + new Brewery(req.body).save() + .then( brewery => res.json(brewery)) + .catch(next); +}); + +breweryRouter.get('/api/brewery/:id', function (req, res, next) { + debug('GET: /api/brewery/:id'); + + Brewery.findById(req.param.id) + .then( brewery => res.json(brewery)) + .catch(next); +}); + +breweryRouter.put('/api/brewery/:id', function (req, res, next) { + debug('GET: /api/brewery/:id'); + + Brewery.findByIdAndUpdate(req.param.id, req.body) + .then( brewery => res.json(brewery)) + .catch(next); +}); + +breweryRouter.delete('/api/brewery/:id', function (req, res, next) { + debug('GET: /api/brewery/:id'); + + Brewery.findByIdAndRemove(req.param.id) + .catch(next); +}); diff --git a/server.js b/server.js index 07b30f2..7ac4392 100644 --- a/server.js +++ b/server.js @@ -4,10 +4,20 @@ const express = require('express'); const morgan = require('morgan'); const cors = require('cors'); const Promise = require('bluebird'); +const mongoose = require('mongoose'); const debug = require('debug')('bew:server'); +const breweryRouter = require('./route/brewery-router.js'); const app = express(); const PORT = process.env.PORT || 3000; +const MONGODB_URI = 'mongodp://localhost/brewerybeers'; + +mongoose.Promise = Promise; +mongoose.connect(MONGODB_URI); + +app.use(cors()); +app.use(morgan('dev')); +app.use(breweryRouter); app.listen(PORT, () => { debug(`listening on ${PORT}`); From 6a93856d05abdaa8ca6bb4abf7742c9c4bb3d880 Mon Sep 17 00:00:00 2001 From: Jamesbillard12 Date: Wed, 2 Aug 2017 16:20:27 -0700 Subject: [PATCH 04/12] POST and GET valid works --- route/brewery-route.js | 8 ++-- server.js | 4 +- test/brewery-test.js | 87 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+), 6 deletions(-) diff --git a/route/brewery-route.js b/route/brewery-route.js index e43a5e5..bef4db0 100644 --- a/route/brewery-route.js +++ b/route/brewery-route.js @@ -17,8 +17,8 @@ breweryRouter.post('/api/brewery', jsonParser, function (req, res, next) { breweryRouter.get('/api/brewery/:id', function (req, res, next) { debug('GET: /api/brewery/:id'); - - Brewery.findById(req.param.id) + console.log('#$)(*#&)$*#&)$&', req.params.id); + Brewery.findById(req.params.id) .then( brewery => res.json(brewery)) .catch(next); }); @@ -26,7 +26,7 @@ breweryRouter.get('/api/brewery/:id', function (req, res, next) { breweryRouter.put('/api/brewery/:id', function (req, res, next) { debug('GET: /api/brewery/:id'); - Brewery.findByIdAndUpdate(req.param.id, req.body) + Brewery.findByIdAndUpdate(req.params.id, req.body) .then( brewery => res.json(brewery)) .catch(next); }); @@ -34,6 +34,6 @@ breweryRouter.put('/api/brewery/:id', function (req, res, next) { breweryRouter.delete('/api/brewery/:id', function (req, res, next) { debug('GET: /api/brewery/:id'); - Brewery.findByIdAndRemove(req.param.id) + Brewery.findByIdAndRemove(req.params.id) .catch(next); }); diff --git a/server.js b/server.js index 7ac4392..bcd3fa1 100644 --- a/server.js +++ b/server.js @@ -6,11 +6,11 @@ const cors = require('cors'); const Promise = require('bluebird'); const mongoose = require('mongoose'); const debug = require('debug')('bew:server'); -const breweryRouter = require('./route/brewery-router.js'); +const breweryRouter = require('./route/brewery-route.js'); const app = express(); const PORT = process.env.PORT || 3000; -const MONGODB_URI = 'mongodp://localhost/brewerybeers'; +const MONGODB_URI = 'mongodb://localhost/brewerybeers'; mongoose.Promise = Promise; mongoose.connect(MONGODB_URI); diff --git a/test/brewery-test.js b/test/brewery-test.js index e69de29..d7a8b1d 100644 --- a/test/brewery-test.js +++ b/test/brewery-test.js @@ -0,0 +1,87 @@ +'use strict'; + +const expect = require('chai').expect; +const request = require('superagent'); +const Brewery = require('../model/brewery.js'); +const PORT = process.env.PORT || 3000; +const mongoose = require('mongoose'); + + + +mongoose.Promise = Promise; +require('../server.js'); + +const url = `http://localhost:${PORT}`; + +const exampleBrewery = { + name: 'test brewery name', + address: 'test address', + phoneNumber: '555-555-5555', +}; + +describe('Brewery Routes', function() { + describe('POST: /api/brewery', function() { + describe('with a valid req body', function() { + after( done => { + if(this.tempBrewery) { + Brewery.remove({}) + .then( () => done()) + .catch(done); + return; + } + done(); + }); + + it('should return a brewery', done => { + request.post(`${url}/api/brewery`) + .send(exampleBrewery) + .end((err,res) => { + if(err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal('test brewery name'); + expect(res.body.address).to.equal('test address'); + expect(res.body.phoneNumber).to.equal('555-555-5555'); + this.tempBrewery = res.body; + done(); + }); + }); + }); + }); + describe('GET: /api/brewery/:id', function() { + describe('with a valid body', function() { + before( done => { + exampleBrewery.timestamp = new Date(); + new Brewery(exampleBrewery).save() + .then( brewery => { + this.tempBrewery = brewery; + done(); + }) + .catch(done); + }); + + after( done => { + delete exampleBrewery.timestamp; + if (this.tempBrewery) { + Brewery.remove({}) + .then( () => done()) + .catch(done); + return; + } + done(); + }); + + it('should return a brewery', done => { + request.get(`${url}/api/brewery/${this.tempBrewery._id}`) + .end( (err, res) => { + console.log(res.body); + if(err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal('test brewery name'); + expect(res.body.address).to.equal('test address'); + expect(res.body.phoneNumber).to.equal('555-555-5555'); + done(); + }); + }); + }); + }); +}); From 63d1ebf037ad7a31dd4095596aee856be70cd915 Mon Sep 17 00:00:00 2001 From: Jamesbillard12 Date: Wed, 2 Aug 2017 18:33:40 -0700 Subject: [PATCH 05/12] post 400 test seems to only work with null --- lib/error-middleware.js | 37 +++++++++++++++++++++++++++++++++++++ model/brewery.js | 8 ++++---- route/brewery-route.js | 1 - server.js | 2 ++ test/brewery-test.js | 18 +++++++++++++++++- 5 files changed, 60 insertions(+), 6 deletions(-) create mode 100644 lib/error-middleware.js diff --git a/lib/error-middleware.js b/lib/error-middleware.js new file mode 100644 index 0000000..3734d60 --- /dev/null +++ b/lib/error-middleware.js @@ -0,0 +1,37 @@ +'use strict'; + +const createError = require('http-errors'); +const debug = require('debug')('beer:error-middleware'); + +module.exports = function(err, req, res, next) { + console.error(err.message); + console.error(err.name); + + if(err.name === 'CastError'){ + err = createError(404, err.message); + res.status(err.status).send(err.message); + next(); + return; + } + + if(err.name === 'ValidationError'){ + err = createError(400, err.message); + res.status(err.status).send(err.message); + next(); + return; + } + + 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/model/brewery.js b/model/brewery.js index b323538..092c5c4 100644 --- a/model/brewery.js +++ b/model/brewery.js @@ -4,10 +4,10 @@ const mongoose = require('mongoose'); const Schema = mongoose.Schema; const brewerySchema = Schema ({ - name: {type: String, require: true}, - address: {type: String, require: true}, - phoneNumber: {type: String, require: true}, - timestamp: {type: Date, require: true} + name: {type: String, required: true, unique: true}, + address: {type: String, required: true}, + phoneNumber: {type: String, required: true}, + timestamp: {type: Date, required: true} }); module.exports = mongoose.model('brewery', brewerySchema); diff --git a/route/brewery-route.js b/route/brewery-route.js index bef4db0..5c8c459 100644 --- a/route/brewery-route.js +++ b/route/brewery-route.js @@ -17,7 +17,6 @@ breweryRouter.post('/api/brewery', jsonParser, function (req, res, next) { breweryRouter.get('/api/brewery/:id', function (req, res, next) { debug('GET: /api/brewery/:id'); - console.log('#$)(*#&)$*#&)$&', req.params.id); Brewery.findById(req.params.id) .then( brewery => res.json(brewery)) .catch(next); diff --git a/server.js b/server.js index bcd3fa1..c4b9d20 100644 --- a/server.js +++ b/server.js @@ -7,6 +7,7 @@ const Promise = require('bluebird'); const mongoose = require('mongoose'); const debug = require('debug')('bew:server'); const breweryRouter = require('./route/brewery-route.js'); +const errors = require('./lib/error-middleware.js'); const app = express(); const PORT = process.env.PORT || 3000; @@ -18,6 +19,7 @@ mongoose.connect(MONGODB_URI); app.use(cors()); app.use(morgan('dev')); app.use(breweryRouter); +app.use(errors); app.listen(PORT, () => { debug(`listening on ${PORT}`); diff --git a/test/brewery-test.js b/test/brewery-test.js index d7a8b1d..6061fa8 100644 --- a/test/brewery-test.js +++ b/test/brewery-test.js @@ -46,6 +46,16 @@ describe('Brewery Routes', function() { }); }); }); + describe('with an invalid request', function() { + it('should return 400', done => { + request.post(`${url}/api/brewery`) + .send(null) + .end((err,res) => { + expect(res.status).to.equal(400); + done(); + }); + }); + }); }); describe('GET: /api/brewery/:id', function() { describe('with a valid body', function() { @@ -73,7 +83,6 @@ describe('Brewery Routes', function() { it('should return a brewery', done => { request.get(`${url}/api/brewery/${this.tempBrewery._id}`) .end( (err, res) => { - console.log(res.body); if(err) return done(err); expect(res.status).to.equal(200); expect(res.body.name).to.equal('test brewery name'); @@ -82,6 +91,13 @@ describe('Brewery Routes', function() { done(); }); }); + it('should return 404', done => { + request.get(`${url}/api/brewery/1231231231241413212`) + .end( (err, res) => { + expect(res.status).to.equal(404); + done(); + }); + }); }); }); }); From 7c58e4c1b994d709a32a30e752ff3b7bf05833f6 Mon Sep 17 00:00:00 2001 From: Jamesbillard12 Date: Wed, 2 Aug 2017 18:36:21 -0700 Subject: [PATCH 06/12] or it can be tested with an empty space 400 --- test/brewery-test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/brewery-test.js b/test/brewery-test.js index 6061fa8..7d8c61f 100644 --- a/test/brewery-test.js +++ b/test/brewery-test.js @@ -49,7 +49,7 @@ describe('Brewery Routes', function() { describe('with an invalid request', function() { it('should return 400', done => { request.post(`${url}/api/brewery`) - .send(null) + .send() .end((err,res) => { expect(res.status).to.equal(400); done(); From d44b0679fb58dcc73be91ce469dee85f672faa00 Mon Sep 17 00:00:00 2001 From: Jamesbillard12 Date: Wed, 2 Aug 2017 18:57:39 -0700 Subject: [PATCH 07/12] added descibe to invalid get req --- test/brewery-test.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/brewery-test.js b/test/brewery-test.js index 7d8c61f..55ca763 100644 --- a/test/brewery-test.js +++ b/test/brewery-test.js @@ -91,6 +91,8 @@ describe('Brewery Routes', function() { done(); }); }); + }); + describe('with an invalid request', function(){ it('should return 404', done => { request.get(`${url}/api/brewery/1231231231241413212`) .end( (err, res) => { From 80b4a71b9a723dd400b2932bb63dd6dd3b005799 Mon Sep 17 00:00:00 2001 From: Jamesbillard12 Date: Wed, 2 Aug 2017 21:58:07 -0700 Subject: [PATCH 08/12] all tests are passing --- model/brewery.js | 2 +- route/brewery-route.js | 29 ++++++++++++----- server.js | 2 +- test/brewery-test.js | 70 ++++++++++++++++++++++++++++++++++++++---- 4 files changed, 88 insertions(+), 15 deletions(-) diff --git a/model/brewery.js b/model/brewery.js index 092c5c4..daf2399 100644 --- a/model/brewery.js +++ b/model/brewery.js @@ -4,7 +4,7 @@ const mongoose = require('mongoose'); const Schema = mongoose.Schema; const brewerySchema = Schema ({ - name: {type: String, required: true, unique: true}, + name: {type: String, required: true}, address: {type: String, required: true}, phoneNumber: {type: String, required: true}, timestamp: {type: Date, required: true} diff --git a/route/brewery-route.js b/route/brewery-route.js index 5c8c459..c38eca4 100644 --- a/route/brewery-route.js +++ b/route/brewery-route.js @@ -15,19 +15,34 @@ breweryRouter.post('/api/brewery', jsonParser, function (req, res, next) { .catch(next); }); -breweryRouter.get('/api/brewery/:id', function (req, res, next) { +breweryRouter.get('/api/brewery/:id', function (req, res, next) { debug('GET: /api/brewery/:id'); Brewery.findById(req.params.id) .then( brewery => res.json(brewery)) .catch(next); }); -breweryRouter.put('/api/brewery/:id', function (req, res, next) { - debug('GET: /api/brewery/:id'); - - Brewery.findByIdAndUpdate(req.params.id, req.body) - .then( brewery => res.json(brewery)) - .catch(next); +breweryRouter.put('/api/brewery/:id', jsonParser, (req, res, next) => { + debug('PUT /api/brewerys/:id'); + + if (Object.keys(req.body).length === 0) { + Brewery.findById(req.params.id) + .then(brewery => { + res.status(400); + res.json(brewery); + }) + .catch(next); + return; + } + + let options = { + runValidator: true, + new: true, + }; + + Brewery.findByIdAndUpdate(req.params.id, req.body, options) + .then(brewery => res.json(brewery)) + .catch(next); }); breweryRouter.delete('/api/brewery/:id', function (req, res, next) { diff --git a/server.js b/server.js index c4b9d20..bec7f74 100644 --- a/server.js +++ b/server.js @@ -11,7 +11,7 @@ const errors = require('./lib/error-middleware.js'); const app = express(); const PORT = process.env.PORT || 3000; -const MONGODB_URI = 'mongodb://localhost/brewerybeers'; +const MONGODB_URI = 'mongodb://localhost/brewery'; mongoose.Promise = Promise; mongoose.connect(MONGODB_URI); diff --git a/test/brewery-test.js b/test/brewery-test.js index 55ca763..56f20e2 100644 --- a/test/brewery-test.js +++ b/test/brewery-test.js @@ -13,12 +13,20 @@ require('../server.js'); const url = `http://localhost:${PORT}`; +let tempBrewery; + const exampleBrewery = { - name: 'test brewery name', - address: 'test address', + name: 'the brewery name', + address: 'the address', phoneNumber: '555-555-5555', }; +const newBrewery = { + name: 'new test brewery name', + address: 'new test address', + phoneNumber: '777-777-7777', +}; + describe('Brewery Routes', function() { describe('POST: /api/brewery', function() { describe('with a valid req body', function() { @@ -38,8 +46,8 @@ describe('Brewery Routes', function() { .end((err,res) => { if(err) return done(err); expect(res.status).to.equal(200); - expect(res.body.name).to.equal('test brewery name'); - expect(res.body.address).to.equal('test address'); + expect(res.body.name).to.equal('the brewery name'); + expect(res.body.address).to.equal('the address'); expect(res.body.phoneNumber).to.equal('555-555-5555'); this.tempBrewery = res.body; done(); @@ -85,8 +93,8 @@ describe('Brewery Routes', function() { .end( (err, res) => { if(err) return done(err); expect(res.status).to.equal(200); - expect(res.body.name).to.equal('test brewery name'); - expect(res.body.address).to.equal('test address'); + expect(res.body.name).to.equal('the brewery name'); + expect(res.body.address).to.equal('the address'); expect(res.body.phoneNumber).to.equal('555-555-5555'); done(); }); @@ -102,4 +110,54 @@ describe('Brewery Routes', function() { }); }); }); + describe('testing PUT /api/brewery', () => { + before( done => { + exampleBrewery.timestamp = new Date(); + new Brewery(exampleBrewery).save() + .then( brewery => { + this.tempBrewery = brewery; + done(); + }) + .catch(done); + }); + + after( done => { + delete exampleBrewery.timestamp; + if (this.tempBrewery) { + Brewery.remove({}) + .then( () => done()) + .catch(done); + return; + } + done(); + }); + it('should respond with a 200 status code and an updated beer object.', () => { + console.log(this.tempBrewery._id); + return request.put(`${url}/api/brewery/${this.tempBrewery._id}`) + .send(newBrewery) + .then(res => { + expect(res.status).to.equal(200); + tempBrewery = res.body; + }); + }); + }); + + it('should respond with a 400 error code.', () => { + return request.post(`${url}/api/brewery`) + .send(tempBrewery) + .then((res) => { + tempBrewery = res.body; + return request.put(`${url}/api/brewery/${this.tempBrewery._id}`) + .send(null); + }) + .catch(err => { + expect(err.status).to.equal(400); + }); + }); + it('should respond with a 404 error code if an ID is not found.', () => { + return request.get(`${url}/api/brewery/12345`) + .catch(err => { + expect(err.status).to.equal(404); + }); + }); }); From 235ea9bdce45777918ff52f1abae2e55ab7262c3 Mon Sep 17 00:00:00 2001 From: Jamesbillard12 Date: Wed, 2 Aug 2017 22:10:43 -0700 Subject: [PATCH 09/12] making 200 tests more robusts --- test/brewery-test.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/brewery-test.js b/test/brewery-test.js index 56f20e2..0cc7e2d 100644 --- a/test/brewery-test.js +++ b/test/brewery-test.js @@ -137,6 +137,9 @@ describe('Brewery Routes', function() { .send(newBrewery) .then(res => { expect(res.status).to.equal(200); + expect(res.body.name).to.equal('new test brewery name'); + expect(res.body.address).to.equal('new test address'); + expect(res.body.phoneNumber).to.equal('777-777-7777'); tempBrewery = res.body; }); }); From 216a959404a57f5d21943fd09549c22a50ffa562 Mon Sep 17 00:00:00 2001 From: Jamesbillard12 Date: Wed, 2 Aug 2017 22:41:54 -0700 Subject: [PATCH 10/12] finished readme --- README.md | 73 ++++++++++--------------------------------------------- 1 file changed, 13 insertions(+), 60 deletions(-) diff --git a/README.md b/README.md index 37f3822..65c9a0f 100644 --- a/README.md +++ b/README.md @@ -1,60 +1,13 @@ -![CF](https://camo.githubusercontent.com/70edab54bba80edb7493cad3135e9606781cbb6b/687474703a2f2f692e696d6775722e636f6d2f377635415363382e706e67) 13: Single Resource Mongo and Express API -=== - -## Submission Instructions - * fork this repository & create a new branch for your work - * write all of your code in a directory named `lab-` + `` **e.g.** `lab-susan` - * push to your repository - * submit a pull request to this repository - * submit a link to your PR in canvas - * write a question and observation on canvas - -## Learning Objectives -* students will be able to work with the MongoDB database management system -* students will understand the primary concepts of working with a NoSQL database management system -* students will be able to create custom data models *(schemas)* through the use of mongoose.js -* students will be able to use mongoose.js helper methods for interacting with their database persistence layer - -## Requirements -#### Configuration -* `package.json` -* `.eslintrc` -* `.gitignore` -* `README.md` - * your `README.md` should include detailed instructions on how to use your API - -#### Feature Tasks -* create an HTTP Server using `express` -* create a resource **model** of your choice that uses `mongoose.Schema` and `mongoose.model` -* use the `body-parser` express middleware to parse the `req` body on `POST` and `PUT` requests -* use the npm `debug` module to log the functions and methods that are being used in your application -* use the express `Router` to create a route for doing **RESTFUL CRUD** operations against your _model_ - -## Server Endpoints -### `/api/resource-name` -* `POST` request - * should pass data as stringifed JSON in the body of a post request to create a new resource - -### `/api/resource-name/:id` -* `GET` request - * should pass the id of a resource through the url endpoint to get a resource - * **this should use `req.params`, not querystring parameters** -* `PUT` request - * should pass data as stringifed JSON in the body of a put request to update a pre-existing resource -* `DELETE` request - * should pass the id of a resource though the url endpoint to delete a resource - * **this should use `req.params`** - -### Tests -* create a test that will ensure that your API returns a status code of 404 for routes that have not been registered -* create a series of tests to ensure that your `/api/resource-name` endpoint responds as described for each condition below: - * `GET` - test 200, returns a resource with a valid body - * `GET` - test 404, respond with 'not found' for valid requests made with an id that was not found - * `PUT` - test 200, returns a resource with an updated body - * `PUT` - test 400, responds with 'bad request' if no request body was provided - * `PUT` - test 404, responds with 'not found' for valid requests made with an id that was not found - * `POST` - test 400, responds with 'bad request' if no request body was provided - * `POST` - test 200, returns a resource for requests made with a valid body - -### Bonus -* **2pts:** a `GET` request to `/api/resource-name` should return an array of stored resources +## James Lab-13 Documentation + + * server.js uses the environmental port (3000) and defines the connection to the database using MongooseJS, sets up the server using Express, and requires route/brewery-router.js, which defines all routes for the single-resource API. + * model/breweryjs defines the breweryconstructor. + * The following methods will return the following results: + * GET localhost:3000/api/brewery/xxxxxxxxxxxxxxxxxxxxxxxx (hexadecimal) - returns status code 200 and a brewery object matching a valid ID. + * POST localhost:3000/api/brewery - returns a 400 error code and the details of the error. + * POST localhost:3000/api/brewery name= grain= hops= yeast= - returns status code 201 and a new breweryobject for a POST request with a valid body. + * PUT localhost:3000/api/brewery - returns a 404 error code and the details of the error if a valid ID is not included. + * PUT localhost:3000/api/brewery/xxxxxxxxxxxxxxxxxxxxxxxx name: , + address:
, phoneNumber: , - returns status code 200 an updated brewery object for PUT request with valid ID and ANY NUMBER of parameters that should be changed, for instance, 'PUT localhost:3000/api/brewery/xxxxxxxxxxxxxxxxxxxxxxxx name='. + * DELETE localhost:3000/api/brewery?id=1 - returns 404 error code and and the details of the error for valid DELETE request made with an ID that was not found. + * DELETE localhost:3000/api/brewery/xxxxxxxxxxxxxxxxxxxxxxxx - returns 204 status code for a DELETE request with a valid ID. From 3a856441310dfd32336cb42c428c60fd1b08a942 Mon Sep 17 00:00:00 2001 From: Jamesbillard12 Date: Wed, 2 Aug 2017 22:43:23 -0700 Subject: [PATCH 11/12] small change to read me --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 65c9a0f..b8d1ca4 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ ## James Lab-13 Documentation * server.js uses the environmental port (3000) and defines the connection to the database using MongooseJS, sets up the server using Express, and requires route/brewery-router.js, which defines all routes for the single-resource API. - * model/breweryjs defines the breweryconstructor. + * model/brewery.js defines the brewery constructor. * The following methods will return the following results: - * GET localhost:3000/api/brewery/xxxxxxxxxxxxxxxxxxxxxxxx (hexadecimal) - returns status code 200 and a brewery object matching a valid ID. + * GET localhost:3000/api/brewery/xxxxxxxxxxxxxxxxxxxxxxxx (:id) - returns status code 200 and a brewery object matching a valid ID. * POST localhost:3000/api/brewery - returns a 400 error code and the details of the error. * POST localhost:3000/api/brewery name= grain= hops= yeast= - returns status code 201 and a new breweryobject for a POST request with a valid body. * PUT localhost:3000/api/brewery - returns a 404 error code and the details of the error if a valid ID is not included. From 44721dd66d215d879a7d9ef20f151d7c754c3120 Mon Sep 17 00:00:00 2001 From: Jamesbillard12 Date: Wed, 2 Aug 2017 22:47:37 -0700 Subject: [PATCH 12/12] minor edits beer to brewery --- lib/error-middleware.js | 2 +- test/brewery-test.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/error-middleware.js b/lib/error-middleware.js index 3734d60..1ef66da 100644 --- a/lib/error-middleware.js +++ b/lib/error-middleware.js @@ -1,7 +1,7 @@ 'use strict'; const createError = require('http-errors'); -const debug = require('debug')('beer:error-middleware'); +const debug = require('debug')('brewery:error-middleware'); module.exports = function(err, req, res, next) { console.error(err.message); diff --git a/test/brewery-test.js b/test/brewery-test.js index 0cc7e2d..7b512bd 100644 --- a/test/brewery-test.js +++ b/test/brewery-test.js @@ -131,7 +131,7 @@ describe('Brewery Routes', function() { } done(); }); - it('should respond with a 200 status code and an updated beer object.', () => { + it('should respond with a 200 status code and an updated brewery object.', () => { console.log(this.tempBrewery._id); return request.put(`${url}/api/brewery/${this.tempBrewery._id}`) .send(newBrewery)