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..3c3629e --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/README.md b/README.md index 8d00d0f..f3daf1e 100644 --- a/README.md +++ b/README.md @@ -1,35 +1,19 @@ -![cf](https://i.imgur.com/7v5ASc8.png) 12: Express Middleware -====== +# Express API - Lab 11 -## 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 +### Description: -## Learning Objectives -* students will be able to work with application, router, and 3rd party middleware through the use of express.js -* students will be able to implement custom middleware through the use of express.js -* students will be able to create custom routers for a specific resource +This app is an API that utilizes the express framework. Following REST architecture the this app allows a resource to be READ, CREATED, UPDATED and DELETED. It runs the appropriate tests for getting the correct data and error messages. -## Requirements +### How to use: -#### Configuration -* `package.json` -* `.eslintrc` -* `.gitignore` -* `README.md` - * your `README.md` should include detailed instructions on how to use your API - -#### Feature Tasks -* create a single resource `express` API that can handle **GET**, **POST**, and **PUT** requests -* use the `http-errors` module to create new errors and associate them with a proper status code -* create an `error-middleware` module to handle errors and *use* it in your server file -* create a `cors-middleware` module that will allow for public use of your API -* create the `deleteItem` and `availIDs` methods and add them to your `storage` module - * these methods should be used to delete a resource (`deleteItem`) and return an array of id's from persisted resource filenames (`availIDs`) -* create the `updateNote`, `fetchNote`, and `fetchIDs` static methods as part of your `Note` model -* create a series of `note-route-tests` to test your **GET**, **POST**, and **PUT** routes - * **hint:** *you'll want to use the `before` and `after` hooks provided by `mocha` in order to create a test note and delete the note after the test has completed* +* Run the server from the command line using `npm run start` +* Open a separate tab in the terminal +* From the second tab start by entering `http [optional request method] :8000/api/song/` +to get all the ids of the songs in local storage +* `GET` or READ requests do not require a request method in the command line + * followed by the songs items id like `/[unique-song-id]'` +* `POST` or CREATE requests are made with `POST` as the request method + * followed by a space then key-value pairs like `name=[item-name]` (no space after parenthesis) + * all key-value pairs must have a space between them +* `DELETE` requests are made like `GET` only with the `DELETE` as the request method +* `PUT` or UPDATE requests are made by entering the `/[id]` followed by a space key value pairs like the `POST` request diff --git a/lib/cors-middleware.js b/lib/cors-middleware.js new file mode 100644 index 0000000..6661797 --- /dev/null +++ b/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/lib/error-middleware.js b/lib/error-middleware.js new file mode 100644 index 0000000..0777e1f --- /dev/null +++ b/lib/error-middleware.js @@ -0,0 +1,21 @@ +'use strict'; + +const createError = require('http-errors'); +const debug = require('debug')('song: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/lib/storage.js b/lib/storage.js new file mode 100644 index 0000000..a066fa7 --- /dev/null +++ b/lib/storage.js @@ -0,0 +1,57 @@ +'use strict'; + +const Promise = require('bluebird'); +const fs = Promise.promisifyAll(require('fs'), { suffix: 'Prom' }); +const createError = require('http-errors'); +const debug = require('debug')('song: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(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) { + 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 item')); + + return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`) + .catch( err => Promise.reject(createError(404, err.message))); +}; + +exports.availIDs = function(schemaName) { + debug('availIDs'); + + 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/model/song.js b/model/song.js new file mode 100644 index 0000000..e015f07 --- /dev/null +++ b/model/song.js @@ -0,0 +1,59 @@ +'use strict'; + +const uuidv4 = require('uuid/v4'); +const createError = require('http-errors'); +const debug = require('debug')('storage:song'); +const storage = require('../lib/storage.js'); + +const Song = module.exports = function(name, band, year) { + debug('song contructor'); + + if (!name) return Promise.reject(createError(400, 'expected name')); + if (!band) return Promise.reject(createError(400, 'expected band')); + if (!year) return Promise.reject(createError(400, 'expected year')); + + this.id = uuidv4(); + this.name = name; + this.band = band; + this.year = year; +}; + +Song.createSong = function(_song) { + debug('createSong'); + + try { + let song = new Song(_song.name, _song.band, _song.year); + return storage.createItem('song', song); + } catch (err) { + return Promise.reject(err); + } +}; + +Song.fetchSong = function(id) { + debug('fetchSong'); + return storage.fetchItem('song', id); +}; + +Song.updateSong = function (id, _song) { + debug('updateSong'); + + return storage.fetchItem('song', id) + .then( song => { + for (var prop in song) { + if (prop === 'id') continue; + if (_song[prop]) song[prop] = _song[prop]; + } + return storage.createItem('song', song); + }) + .catch( err => Promise.reject(createError(404, err.message))); +}; + +Song.deleteSong = function(id) { + debug('deleteSong'); + return storage.deleteItem('song', id); +}; + +Song.fetchIDs = function() { + debug('fetchIDs'); + return storage.availIDs('song'); +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..abc9503 --- /dev/null +++ b/package.json @@ -0,0 +1,35 @@ +{ + "name": "12-express-middleware", + "version": "1.0.0", + "description": "![cf](https://i.imgur.com/7v5ASc8.png) 12: Express Middleware ======", + "main": "server.js", + "scripts": { + "test": "DEBUG='song*' mocha", + "start": "DEBUG='song*' node server.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nickjaz/12-express-middleware.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/nickjaz/12-express-middleware/issues" + }, + "homepage": "https://github.com/nickjaz/12-express-middleware#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/route/song-router.js b/route/song-router.js new file mode 100644 index 0000000..84155e8 --- /dev/null +++ b/route/song-router.js @@ -0,0 +1,41 @@ +'use strict'; + +const Router = require('express').Router; +const jsonParser = require('body-parser').json(); +const debug = require('debug')('song:song-router'); +const Song = require('../model/song.js'); +const songRouter = new Router(); + +songRouter.post('/api/song', jsonParser, function(req, res, next){ + debug('POST: /api/song'); + + Song.createSong(req.body) + .then( song => res.json(song)) + .catch( err => next(err)); +}); + +songRouter.get('/api/song/:id', function(req, res, next) { + debug('GET: /api/song/:id'); + + Song.fetchSong(req.params.id) + .then( song => res.json(song)) + .catch( err => next(err)); +}); + +songRouter.get('/api/song', function(req, res, next) { + debug('GET: /api/song'); + + Song.fetchIDs() + .then( ids => res.json(ids)) + .catch( err => next(err)); +}); + +songRouter.put('/api/song/:id', jsonParser, function(req, res, next) { + debug('PUT: /api/song/:id'); + + Song.updateSong(req.params.id, req.body) + .then( song => res.json(song)) + .catch( err => next(err)); +}); + +module.exports = songRouter; diff --git a/server.js b/server.js new file mode 100644 index 0000000..10d15e5 --- /dev/null +++ b/server.js @@ -0,0 +1,22 @@ +'use strict'; + +const morgan = require('morgan'); +const express = require('express'); +const createError = require('http-errors'); +const debug = require('debug')('song:server'); + +const songRouter = require('./route/song-router.js'); +const cors = require('./lib/cors-middleware.js'); +const errors = require('./lib/error-middleware.js'); + +const PORT = process.env.PORT || 3000; +const app = express(); + +app.use(morgan('dev')); +app.use(cors); +app.use(songRouter); +app.use(errors); + +app.listen(PORT, () => { + console.log(`server up: ${PORT}`); +}); diff --git a/test/song-route-test.js b/test/song-route-test.js new file mode 100644 index 0000000..f3c4454 --- /dev/null +++ b/test/song-route-test.js @@ -0,0 +1,111 @@ +'use strict'; + +const expect = require('chai').expect; +const request = require('superagent'); +const Song = require('../model/song.js'); +const url = 'http://localhost:8000'; + +require('../server.js'); + +const exampleSong = { + name: 'example name', + band: 'example band', + year: 'example year' +}; + +describe('Song Routes', function() { + + describe('GET: /api/song', function() { + describe('with valid id', function() { + before(done => { + Song.createSong(exampleSong) + .then(song => { + this.tempSong = song; + done(); + }) + .catch( err => done(err)); + }); + + after( done => { + Song.deleteSong(this.tempSong.id) + .then( () => done()) + .catch( err => done(err)); + }); + + it('should return a song', done => { + request.get(`${url}/api/song/${this.tempSong.id}`) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.id).to.equal(this.tempSong.id); + expect(res.body.name).to.equal(this.tempSong.name); + expect(res.body.band).to.equal(this.tempSong.band); + expect(res.body.year).to.equal(this.tempSong.year); + done(); + }); + }); + }); + }); + + describe('POST: /api/song', function() { + describe('with valid body', function() { + after( done => { + if(this.tempSong) { + Song.deleteSong(this.tempSong.id) + .then( () => done()) + .catch( err => done(err)); + } + }); + + it('should return a song', done => { + request.post(`${url}/api/song`) + .send(exampleSong) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal(exampleSong.name); + expect(res.body.band).to.equal(exampleSong.band); + expect(res.body.year).to.equal(exampleSong.year); + this.tempSong = res.body; + done(); + }); + }); + }); + }); + + describe('PUT: /api/song', function() { + describe('with a valid id and body', function() { + before( done => { + Song.createSong(exampleSong) + .then( song => { + this.tempSong = song; + done(); + }) + .catch( err => done(err)); + }); + + after( done => { + if (this.tempSong) { + Song.deleteSong(this.tempSong.id) + .then( () => done()) + .catch(done); + } + }); + + it('should return a note', done => { + let updateSong = { name: 'new name', band: 'new band', year: 'new year' }; + request.put(`${url}/api/song/${this.tempSong.id}`) + .send(updateSong) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.id).to.equal(this.tempSong.id); + for (var prop in updateSong) { + expect(res.body[prop]).to.equal(updateSong[prop]); + } + done(); + }); + }); + }); + }); +});