diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..82ff623 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,5 @@ +**/node_modules/* +**/vendor/* +**/*.min.js +**/coverage/* +**/build/* \ No newline at end of file diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 0000000..b663d77 --- /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" +} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..95c57d9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,137 @@ +# 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 +Contact GitHub API Training Shop Blog About diff --git a/README.md b/README.md index feb511f..9371c4f 100644 --- a/README.md +++ b/README.md @@ -1,53 +1,9 @@ -![cf](https://i.imgur.com/7v5ASc8.png) 11: Single Resource Express API -====== +# Baked Goods 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 +This REST API uses express to route incoming requests. -## 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 +# Endpoints -## 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 +**GET** : '/' +**POST** : '/api/bake?id= +**DELETE** : '/api/bake?id= diff --git a/data/bake/b78e48ca-3201-4aeb-8f05-158a6bfab915.json b/data/bake/b78e48ca-3201-4aeb-8f05-158a6bfab915.json new file mode 100644 index 0000000..0c9136c --- /dev/null +++ b/data/bake/b78e48ca-3201-4aeb-8f05-158a6bfab915.json @@ -0,0 +1 @@ +{"id":"b78e48ca-3201-4aeb-8f05-158a6bfab915","bakedGood":"muffin","description":"naked cupcake","calories":255} \ No newline at end of file diff --git a/lib/storage.js b/lib/storage.js new file mode 100644 index 0000000..ab17ccd --- /dev/null +++ b/lib/storage.js @@ -0,0 +1,49 @@ +'use strict'; + +const Promise = require('bluebird'); +const fs = Promise.promisifyAll(require('fs'), { suffix: 'Prom' }); +const createError = require('http-errors'); +const debug = require('debug')('bake:storage'); + +module.exports = exports = {}; + +exports.createItem = function(schemaName, item) { + debug('create item'); + + 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( () => Promise.reject(createError(400, 'unable to write file'))); +}; + +exports.fetchItem = function(schemaName, id) { + debug('fetch item'); + + 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(404, 'expected SOMETHING')); + } + }) + .catch( () => Promise.reject(createError(404, 'no file found'))); +}; + +exports.deleteItem = function(schemaName, id) { + debug('delete item'); + + 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( () => console.log(`${id} deleted`)) + .catch( err => Promise.reject(err)); +}; diff --git a/model/bake.js b/model/bake.js new file mode 100644 index 0000000..293f93e --- /dev/null +++ b/model/bake.js @@ -0,0 +1,41 @@ +'use strict'; + +const uuidv4 = require('uuid/v4'); +const createError = require('http-errors'); +const debug = require('debug')('bake:bake'); +const storage = require('../lib/storage.js'); + +const Bake = module.exports = function(bakedGood, description, calories) { + if (!bakedGood) throw createError(400, 'expected baked good'); + if (!description) throw createError(400, 'expected description'); + if (!calories) throw createError(400, 'expected expected calories'); + + this.id = uuidv4(); + this.bakedGood = bakedGood; + this.description = description; + this.calories = calories; +}; + +Bake.createBakedGood = function(_bake) { + debug('createBakedGood'); + + try { + let bake = new Bake(_bake.bakedGood, _bake.description, _bake.calories); + return storage.createItem('bake', bake); + } catch (err) { + return Promise.reject(err); + } +}; + +Bake.fetchBakedGood = function(id) { + debug('fetchBakedGood'); + + return storage.fetchItem('bake', id); +}; + +Bake.deleteBakedGood = function(id) { + debug('deleteBakedGood'); + + return storage.deleteItem('bake', id); +}; + diff --git a/package.json b/package.json new file mode 100644 index 0000000..9401abc --- /dev/null +++ b/package.json @@ -0,0 +1,38 @@ +{ + "name": "11-express-api", + "version": "1.0.0", + "description": "![cf](https://i.imgur.com/7v5ASc8.png) 11: Single Resource Express API ======", + "main": "server.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "mocha", + "start": "DEBUG='bake*' node server.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ohjonah/11-express-api.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/ohjonah/11-express-api/issues" + }, + "homepage": "https://github.com/ohjonah/11-express-api#readme", + "devDependencies": { + "bluebird": "^3.5.0", + "body-parser": "^1.17.2", + "chai": "^4.1.0", + "debug": "^2.6.8", + "http-errors": "^1.6.1", + "mocha": "^3.5.0", + "morgan": "^1.8.2", + "superagent": "^3.5.2", + "uuid": "^3.1.0" + }, + "dependencies": { + "express": "^4.15.3" + } +} diff --git a/server.js b/server.js new file mode 100644 index 0000000..8930fee --- /dev/null +++ b/server.js @@ -0,0 +1,63 @@ +'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')('bake:server'); +const Bake = require('./model/bake.js'); + +const PORT = process.env.PORT || 3000; +const app = express(); + +app.use(morgan('dev')); + +app.get('/test', function(req, res) { + debug('GET: /test'); + + res.json({ msg: 'hello from /test'}); +}); + +app.post('/api/bake', jsonParser, function(req, res, next) { + debug('POST: /api/bake'); + + Bake.createBakedGood(req.body) + .then( bake => res.json(bake)) + .catch( err => next(err)); +}); + +app.get('/api/bake', function(req, res, next) { + debug('GET: /api/bake'); + + Bake.fetchBakedGood(req.query.id) + .then( bake => res.json(bake)) + .catch( err => next(err)); +}); + +app.delete('/api/bake', function(req, res, next) { + debug('DELETE: /api/bake'); + + Bake.deleteBakedGood(req.query.id) + .then( () => { + res.status(204).end(); + }) + .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, () => { + debug(`Server listening on PORT: ${PORT}`); +}); \ No newline at end of file diff --git a/test/bake-route-test.js b/test/bake-route-test.js new file mode 100644 index 0000000..4020775 --- /dev/null +++ b/test/bake-route-test.js @@ -0,0 +1,97 @@ +'use strict'; + +const request = require('superagent'); +const expect = require('chai').expect; + +require('../server.js'); + +describe('Baked Good Routes', function() { + var bake = null; + + describe('GET: /test', function() { + it('should return msg', done => { + request.get('localhost:8000/test') + .end((err, res) => { + expect(res.status).to.equal(200); + done(); + }); + }); + }); + + describe('POST: 400/Bad Request', function() { + it('should return 400', done => { + request.post('localhost:8000/api/bake') + .end((err, res) => { + expect(res.status).to.equal(400); + done(); + }); + }); + }); + + describe('POST: /api/bake', function() { + it('should make a baked good', function(done) { + request.post('localhost:8000/api/bake') + .send({ + bakedGood: 'muffin', + description: 'naked cupcake', + calories: 255 + }) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.bakedGood).to.equal('muffin'); + expect(res.body.description).to.equal('naked cupcake'); + expect(res.body.calories).to.equal(255); + + bake = res.body; + done(); + }); + }); + }); + + describe('GET: /api/bake', function() { + it('should return a baked good', function(done) { + request.get(`localhost:8000/api/bake?id=${bake.id}`) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.bakedGood).to.equal('muffin'); + expect(res.body.description).to.equal('naked cupcake'); + expect(res.body.calories).to.equal(255); + done(); + }); + }); + }); + + describe('GET: 404/Unregistered Route', () => { + it('should return a 404', done => { + request.get('localhost:8000/api/baykk') + .end((err, res) => { + expect(res.status).to.equal(404); + done(); + }); + }); + }); + + describe('GET: 400/No ID', () => { + it('should return a 400', done => { + request.get('localhost:8000/api/bake') + .end((err, res) => { + expect(res.status).to.equal(400); + done(); + }); + }); + }); + + describe('DELETE: /api/bake', function() { + it('should delete a baked good', done => { + request.delete(`localhost:8000/api/bake?id=${bake.id}`) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(204); + expect(res.body.bakedGood).to.equal(undefined); + done(); + }); + }); + }); +}); \ No newline at end of file