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 feb511f..051bd82 100644 --- a/README.md +++ b/README.md @@ -1,53 +1,75 @@ -![cf](https://i.imgur.com/7v5ASc8.png) 11: Single Resource 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 create a single resource API using the express framework -* students will be able to leverage 3rd party helper modules for debugging, logging, and handling errors - -## 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 object constructor that creates a _simple resource_ with at least 3 properties - * it can **not** have the same properties as the in-class sample code (other than the `id`) - * a unique `id` property should be included *(node-uuid)* - * include two additional properties of your choice -* use the JSON parser included with the `body-parser` module as a middleware component to parse the request body on `POST` and `PUT` routes -* use the npm `debug` module to log the methods in your application -* create an `npm` script to automate the `debug` process and start the server -* persist your API data using the storage module and file system persistence - -#### Server Endpoints -* **`/api/simple-resource-name`** -* `POST` request - * pass data as stringifed JSON in the body of a **POST** request to create a new resource -* `GET` request - * pass `?id=` as a query string parameter to retrieve a specific resource (as JSON) -* `DELETE` request - * pass `?id=` in the query string to **DELETE** a specific resource - * this should return a 204 status code with no content in the body - -#### Tests -* write a test to ensure that your api returns a status code of 404 for routes that have not been registered -* write tests to ensure the `/api/simple-resource-name` endpoint responds as described for each condition below: - * `GET`: test 404, it should respond with 'not found' for valid requests made with an id that was not found - * `GET`: test 400, it should respond with 'bad request' if no id was provided in the request - * `GET`: test 200, it should contain a response body for a request made with a valid id - * `POST`: test 400, it should respond with 'bad request' if no request body was provided or the body was invalid - * `POST`: test 200, it should respond with the body content for a post request with a valid body +# Vanilla API Persistence - 09 Lab + +## Description: +This app builds out an API where data is stored in the file system. This API stores beer data with the schema of name, style, and IBU. + +## API: +The URL endpoint to access the api is `/api/beer`. Using REST architecture the data is read, written and deleted using `GET`, `POST` and `DELETE` requests. + +### POST: + +``` +request.post('localhost:8000/api/beer') +.send({ name: 'Have a Nice Day IPA', style: 'IPA', IBU: '43' }) +``` + +This is a representation of the POST method. You can see that we first make a request to post to +``` +localhost:8000 +``` +with a route of +``` +/api/beer +``` +Once the connection has bee made we send our beer in +``` +.send({ name: 'Have a Nice Day IPA', style: 'IPA', IBU: '43' }) +``` +format. This will respond with 200 if the request was made or 400 if not. + +### GET + +``` +request.get(`localhost:8000/api/beer?id=${beer.id}`) +``` +This is a representation of the GET method. You can see that we first make a request to post to + +``` +localhost:8000 +``` +with a route of + +``` +/api/beer +``` + +finally with finish the request with reference to a specific id which was generated with uuid + +``` +?id=${beer.id} +``` + +This will respond with 200 if the request was made, 404 if not found or 400 if the request was made in wrong format. + +### DELETE + +``` +request.delete(`localhost:8000/api/beer?id=${beer.id}`) +``` + +This is a representation of the POST method. You can see that we first make a request to post to + +``` +localhost:8000 +``` +with a route of + +``` +/api/beer +``` +finally with finish the request with reference to a specific id which was generated with uuid +``` +?id=${beer.id} +``` + +This will respond with 200 if the request was made, 404 if not found or 400 if the request was made in wrong format. diff --git a/lib/storage.js b/lib/storage.js new file mode 100644 index 0000000..122caae --- /dev/null +++ b/lib/storage.js @@ -0,0 +1,53 @@ +'use strict'; + +const Promise = require('bluebird'); +const fs = Promise.promisifyAll(require('fs'), { suffix: 'Prom' }); +const createError = require('http-errors'); +const debug = require('debug')('note:storage'); + +module.exports = exports = {}; + +exports.createItem = function(schemaName, item) { + debug('createItem'); + if (!schemaName) return Promise.reject(createError(400, 'expected schema name')); + 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)); +}; + +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(err); + } + }) + .catch( () => Promise.reject(createError(404, 'not found'))); +}; + +exports.deleteItem = 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.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`) + .then( () => { + try { + console.log('your file was deleted'); + + } catch (err) { + return Promise.reject(err); + } + }) + .catch( err => Promise.reject(err)); +}; diff --git a/model/beer.js b/model/beer.js new file mode 100644 index 0000000..52931a2 --- /dev/null +++ b/model/beer.js @@ -0,0 +1,40 @@ +'use strict'; + +const uuidv4 = require('uuid/v4'); +const createError = require('http-errors'); +const debug = require('debug')('beer:beer'); +const storage = require('../lib/storage.js'); + +const Beer = module.exports = function(name, style, IBU) { + debug('beer constructor'); + + if (!name) throw new Error('expected content'); + if (!style) throw new Error('expected content'); + if (!IBU) throw new Error('expected content'); + + this.id = uuidv4(); + this.name = name; + this.style = style; + this.IBU = IBU; +}; + +Beer.createBeer = function(_beer) { + debug('createBeer'); + + try { + let beer = new Beer(_beer.name, _beer.style, _beer.IBU); + return storage.createItem('beer', beer); + } catch (err) { + return Promise.reject(createError(400, 'bad request')); + } +}; + +Beer.fetchBeer = function(id) { + debug('fetchBeer'); + return(storage.fetchItem('beer', id)); +}; + +Beer.deleteBeer = function(id) { + debug('deleteBeer'); + return(storage.deleteItem('beer', id)); +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..356e038 --- /dev/null +++ b/package.json @@ -0,0 +1,35 @@ +{ + "name": "11-express-api", + "version": "1.0.0", + "description": "![cf](https://i.imgur.com/7v5ASc8.png) 11: Single Resource Express API ======", + "main": "server.js", + "scripts": { + "test": "mocha", + "start": "DEBUG='beer*' node server.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Jamesbillard12/11-express-api.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/Jamesbillard12/11-express-api/issues" + }, + "homepage": "https://github.com/Jamesbillard12/11-express-api#readme", + "dependencies": { + "bluebird": "^3.5.0", + "body-parser": "^1.17.2", + "debug": "^2.6.8", + "express": "^4.15.3", + "http-errors": "^1.6.1", + "morgan": "^1.8.2", + "uuid": "^3.1.0" + }, + "devDependencies": { + "chai": "^4.1.0", + "mocha": "^3.5.0", + "superagent": "^3.5.2" + } +} diff --git a/server.js b/server.js new file mode 100644 index 0000000..0c02acc --- /dev/null +++ b/server.js @@ -0,0 +1,57 @@ +'use strict'; + +const express = require('express'); +const morgan = require('morgan'); +const createError = require('http-errors'); +const jsonParser = require('body-parser').json(); +const debug = require('debug')('beer:server'); +const Beer = require('./model/beer.js'); + +const PORT = process.env.PORT || 3000; +const app = express(); + +app.use(morgan('dev')); + +app.post('/api/beer', jsonParser, function (req, res, next) { + debug('POST: /api/beer'); + + Beer.createBeer(req.body) + .then( beer => res.status(200).json(beer)) + .catch( err => next(err)); +}); + +app.get('/api/beer', function(req, res, next) { + debug('GET: /api/beer'); + Beer.fetchBeer(req.query.id) + .then( beer => res.json(beer)) + .catch( err => next(err)); +}); + +app.delete('/api/beer', function(req, res, next) { + debug('DELETE: /api/beet'); + Beer.deleteBeer(req.query.id) + .then( () => res.status(204).send('Beer Deleted')) + .catch( err => next(err)); +}); + +app.use(function(err, req, res, next){ //eslint-disable-line + debug('error middleware'); + console.error(err.message); + + if(err.status === 404){ + res.status(404).send(err.message); + return; + } + + if(err.status === 400){ + res.status(400).send(err.message); + return; + } + + err = createError(500, err.message); + res.status(err.status).send(err.name); +}); + +app.listen(PORT, () => { + debug('server up:', PORT); +}); diff --git a/test/beer-route-test.js b/test/beer-route-test.js new file mode 100644 index 0000000..f88b0b5 --- /dev/null +++ b/test/beer-route-test.js @@ -0,0 +1,74 @@ +'use strict'; + +const request = require('superagent'); +const expect = require('chai').expect; + +require('../server.js'); + +describe('Beer Routes', function() { + var beer = null; + + describe('POST: /api/beer', function() { + it('should return a beer', function(done) { + request.post('localhost:8000/api/beer') + .send({ name: 'test name', style: 'test style', IBU: 'test IBU' }) + .end((err, res) => { + if (err) return done(err); + console.log(res.body); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal('test name'); + expect(res.body.style).to.equal('test style'); + expect(res.body.IBU).to.equal('test IBU'); + beer = res.body; + done(); + }); + }); + it('should return 400', function(done) { + request.post('localhost:8000/api/beer') + .send({}) + .end((err, res) => { + expect(res.status).to.equal(400); + done(); + }); + }); + }); + + describe('GET: /api/beer', function() { + it('should return a beer', function(done) { + request.get(`localhost:8000/api/beer?id=${beer.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.style).to.equal('test style'); + expect(res.body.IBU).to.equal('test IBU'); + done(); + }); + }); + it('should return 404 not found', function(done) { + request.get('localhost:8000/api/beer?id=6194fa11-758f-477f-a597-61a5a8ca65cb') + .end((err, res) => { + expect(res.status).to.equal(404); + done(); + }); + }); + it('should return 400 bad request', function(done) { + request.get('localhost:8000/api/beer?id=') + .end((err, res) => { + expect(res.status).to.equal(400); + done(); + }); + }); + }); + + describe('DELETE: /api/beer', function() { + it('should return 204', function(done) { + request.delete(`localhost:8000/api/beer?id=${beer.id}`) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(204); + done(); + }); + }); + }); +});