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/README.md b/README.md index 37f3822..b8d1ca4 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/brewery.js defines the brewery constructor. + * The following methods will return the following results: + * 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. + * 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. diff --git a/lib/error-middleware.js b/lib/error-middleware.js new file mode 100644 index 0000000..1ef66da --- /dev/null +++ b/lib/error-middleware.js @@ -0,0 +1,37 @@ +'use strict'; + +const createError = require('http-errors'); +const debug = require('debug')('brewery: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 new file mode 100644 index 0000000..daf2399 --- /dev/null +++ b/model/brewery.js @@ -0,0 +1,13 @@ +'use strict'; + +const mongoose = require('mongoose'); +const Schema = mongoose.Schema; + +const brewerySchema = Schema ({ + name: {type: String, required: 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/package.json b/package.json new file mode 100644 index 0000000..8af7a90 --- /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": "DEBUG='bew*' mocha", + "start": "DEBUG='bew*' 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..c38eca4 --- /dev/null +++ b/route/brewery-route.js @@ -0,0 +1,53 @@ +'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.params.id) + .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) { + debug('GET: /api/brewery/:id'); + + Brewery.findByIdAndRemove(req.params.id) + .catch(next); +}); diff --git a/server.js b/server.js new file mode 100644 index 0000000..bec7f74 --- /dev/null +++ b/server.js @@ -0,0 +1,26 @@ +'use strict'; + +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-route.js'); +const errors = require('./lib/error-middleware.js'); + +const app = express(); +const PORT = process.env.PORT || 3000; +const MONGODB_URI = 'mongodb://localhost/brewery'; + +mongoose.Promise = Promise; +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 new file mode 100644 index 0000000..7b512bd --- /dev/null +++ b/test/brewery-test.js @@ -0,0 +1,166 @@ +'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}`; + +let tempBrewery; + +const exampleBrewery = { + 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() { + 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('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(); + }); + }); + }); + describe('with an invalid request', function() { + it('should return 400', done => { + request.post(`${url}/api/brewery`) + .send() + .end((err,res) => { + expect(res.status).to.equal(400); + 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) => { + if(err) return done(err); + expect(res.status).to.equal(200); + 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(); + }); + }); + }); + describe('with an invalid request', function(){ + it('should return 404', done => { + request.get(`${url}/api/brewery/1231231231241413212`) + .end( (err, res) => { + expect(res.status).to.equal(404); + done(); + }); + }); + }); + }); + 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 brewery 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); + 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; + }); + }); + }); + + 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); + }); + }); +});