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..04415d6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,95 @@ + +# Created by https://www.gitignore.io/api/node,macos + +### 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 + +Test Data +data/ + +# End of https://www.gitignore.io/api/node,macos diff --git a/README.md b/README.md index 27b130b..840dd79 100644 --- a/README.md +++ b/README.md @@ -1,48 +1,70 @@ -![CF](https://camo.githubusercontent.com/70edab54bba80edb7493cad3135e9606781cbb6b/687474703a2f2f692e696d6775722e636f6d2f377635415363382e706e67) Lab 11: Single Resource Express API -=== - -## To Submit this Assignment - * Fork this repository - * Write all of your code in a directory named `lab-` + `` **e.g.** `lab-brian` - * 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 - -## Include - * `package.json` - * `.eslintrc` - * `gulpfile.js` - * `.gitignore` - * `README.md` - * your `README.md` should include detailed instructions on how to use your API - -## Description - * 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 +### Single Resource API + +This single resource API uses the Express framework along with other native Node modules to help me keep track of all of my sweet bikes. It leverages the Bluebird promisifying library on the File System module to add a layer of persistence: + +* [markdown-it] - Markdown parser done right. Fast and easy to extend. +* [node.js] - evented I/O for the backend +* [Express] - fast node.js network app framework [@tjholowaychuk] +* [Gulp] - the streaming build system + +And of course Dillinger itself is open source with a [public repository][repo] + on GitHub. + +### Installation + +Dillinger requires [Node.js](https://nodejs.org/) v4+ to run. + +Clone down the repo, install the dependencies and devDependencies and start the server. + +```sh +$ git clone git@github.com:dkulp23/11-single_resource_express_api.git +$ npm install -d +$ npm start +``` + +Install and use the HTTPie library to make a POST request to the API: + +```sh +$ brew install httpie +$ http POST :3000/api/bike brand="rodriguez" type="sweet fixie brah" +``` +To GET the records you've created, you'll first need to copy & past their unique ID: +``` +$ http :3000/api/bike/ +``` +And if you want to DELETE it: +``` +$ http DELETE :3000/api/bike/ +``` + +Passing 8 tests on 3 defined routes (POST, GET, DELETE). PUT returns 404 error. + +Gulpfile default set to run linter and mocha tests. +```sh +$ gulp +``` + +License +---- + +MIT + + +**Free Software, Hell Yeah!** + +[//]: # (These are reference links used in the body of this note and get stripped out when the markdown processor does its job. There is no need to format nicely because it shouldn't be seen. Thanks SO - http://stackoverflow.com/questions/4823468/store-comments-in-markdown-syntax) + + + [repo]: + [git-repo-url]: + [john gruber]: + [df1]: + [markdown-it]: + [Ace Editor]: + [node.js]: + [Twitter Bootstrap]: + [jQuery]: + [@tjholowaychuk]: + [express]: + [AngularJS]: + [Gulp]: diff --git a/gulpfile.js b/gulpfile.js new file mode 100644 index 0000000..d2df2c1 --- /dev/null +++ b/gulpfile.js @@ -0,0 +1,23 @@ +'use strict'; + +const gulp = require('gulp'); +const eslint = require('gulp-eslint'); +const mocha = require('gulp-mocha'); + +gulp.task('lint', function() { + return gulp.src(['**/*.js', '!node_modules']) + .pipe(eslint()) + .pipe(eslint.format()) + .pipe(eslint.failAfterError()); +}); + +gulp.task('test', function() { + gulp.src('./test/*-test.js', { read: false }) + .pipe(mocha({ reporter: 'spec'})); +}); + +gulp.task('dev', function() { + gulp.watch(['**/*.js', '!node_modules'], ['lint', 'test']); +}); + +gulp.task('default', ['lint', 'test']); diff --git a/lib/storage.js b/lib/storage.js new file mode 100644 index 0000000..89205c8 --- /dev/null +++ b/lib/storage.js @@ -0,0 +1,71 @@ +'use strict'; + +const Promise = require('bluebird'); +const createError = require('http-errors'); +const debug = require('debug')('bike:storage'); +const fs = Promise.promisifyAll(require('fs'), {suffix: 'Prom'}); + +module.exports = exports = {}; + +exports.createItem = function(schemaName, item) { + debug('createItem'); + + if (!schemaName) return Promise.reject(new createError(400, 'expected schema name')); + if (!item) return Promise.reject(new createError(400, 'expected item')); + + let json = JSON.stringify(item); + return fs.writeFileProm(`${__dirname}/../data/${schemaName}/${item.id}.json`, json) + .then( () => item) + .catch( err => { + return Promise.reject(new createError(500, err.message)); + }); +}; + +exports.fetchItem = function(schemaName, id) { + debug('fetchItem'); + if (!schemaName) return Promise.reject(new createError(400, 'schema expected')); + if (!id) return Promise.reject(new createError(400, 'id expected')); + + return fs.readFileProm(`${__dirname}/../data/${schemaName}/${id}.json`) + .then( data => { + try { + let foundItem = JSON.parse(data.toString()); + return foundItem; + } catch (err) { + return Promise.reject(new createError(500, err.message)); + } + }) + .catch( err => { + return Promise.reject(new createError(404, err.message)); + }); +}; + +exports.deleteItem = function(schemaName, id) { + debug('deleteItem'); + + if (!schemaName) return Promise.reject(new createError(400, 'schema expected')); + if (!id) return Promise.reject(new createError(400, 'id expected')); + + return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`) + .then() + .catch( err => { + return Promise.reject(new createError(500, err.message)); + }); +}; + +exports.fetchAllItems = function(schemaName) { + debug('fetchAllItems'); + + if(!schemaName) return Promise.reject(new createError(400, 'schema expected')); + + return fs.readdirProm(`${__dirname}/../data/${schemaName}`) + .then( items => { + try { + let itemNames = items.join(', '); + return itemNames; + } catch (err) { + return Promise.reject(new createError(500, err.message)); + } + }) + .catch( err => Promise.reject(new createError(404, err.message))); +}; diff --git a/model/bike.js b/model/bike.js new file mode 100644 index 0000000..5b96814 --- /dev/null +++ b/model/bike.js @@ -0,0 +1,38 @@ +'use strict'; + +const uuid = require('node-uuid'); +const debug = require('debug')('bike:bike'); +const createError = require('http-errors'); +const storage = require(`${__dirname}/../lib/storage.js`); + +const Bike = module.exports = function(brand, type) { + debug('bike constructor'); + + if (!brand) throw createError(400, 'bike brand expected'); + if (!type) throw createError(400, 'bike type expected'); + + this.id = uuid.v1(); + this.brand = brand; + this.type = type; +}; + +Bike.createBike = function(_bike) { + debug('createBike'); + + try { + let bike = new Bike(_bike.brand, _bike.type); + return storage.createItem('bike', bike); + } catch(err) { + return Promise.reject(err); + } +}; + +Bike.fetchBike = function(id) { + debug('fetchBike'); + return storage.fetchItem('bike', id); +}; + +Bike.deleteBike = function(id) { + debug('deleteBike'); + return storage.deleteItem('bike', id); +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..7b069d1 --- /dev/null +++ b/package.json @@ -0,0 +1,36 @@ +{ + "name": "lab-dana", + "version": "1.0.0", + "description": "![CF](https://camo.githubusercontent.com/70edab54bba80edb7493cad3135e9606781cbb6b/687474703a2f2f692e696d6775722e636f6d2f377635415363382e706e67) Lab 11: Single Resource Express API ===", + "main": "server.js", + "dependencies": { + "bluebird": "^3.4.7", + "body-parser": "^1.16.1", + "debug": "^2.6.1", + "express": "^4.14.1", + "http-errors": "^1.6.1", + "morgan": "^1.8.1", + "node-uuid": "^1.4.7" + }, + "devDependencies": { + "chai": "^3.5.0", + "chai-http": "^3.0.0", + "gulp-eslint": "^3.0.1", + "gulp-mocha": "^4.0.1", + "superagent": "^3.5.0" + }, + "scripts": { + "start": "DEBUG='bike*' nodemon server.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/dkulp23/11-single_resource_express_api.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/dkulp23/11-single_resource_express_api/issues" + }, + "homepage": "https://github.com/dkulp23/11-single_resource_express_api#readme" +} diff --git a/server.js b/server.js new file mode 100644 index 0000000..b2ef039 --- /dev/null +++ b/server.js @@ -0,0 +1,66 @@ +'use strict'; + +const express = require('express'); +const debug = require('debug')('bike:server'); +const morgan = require('morgan'); +const createError = require('http-errors'); +const jsonParser = require('body-parser').json(); +const PORT = process.env.PORT || 3000; +const app = express(); + +const Bike = require('./model/bike.js'); + +app.use(morgan('dev')); + +app.post('/api/bike', jsonParser, function(req, res, next) { + debug('POST: /api/bike'); + + Bike.createBike(req.body) + .then( bike => res.json(bike)) + .catch( err => next(err)); +}); + +app.get('/api/bike/:id', function(req, res, next) { + debug('GET: /api/bike'); + + Bike.fetchBike(req.params.id) + .then( bike => res.json(bike)) + .catch( err => next(err)); +}); + +app.delete('/api/bike/:id', function(req, res, next) { + debug('DELETE: /api/bike'); + + Bike.deleteBike(req.params.id) + .then(res.status(204).send()) + .catch( err => next(err)); +}); + +app.put('*', function(req, res, next) { + debug('* for undefined put routes'); + + next(new createError(404, 'Not Found')); +}); + +app.get('/api/bike/', function(req, res, next) { + debug('get req without id'); + + next(new createError(400, 'Bad Request')); +}); + +app.use(function(err, req, res, next) { + debug('error handler middleware'); + + if (err.status) { + res.status(err.status).send(err.name); + return; + } + + err = createError(500, err.message); + res.status(err.status).send(err.name); + next(); +}); + +app.listen(PORT, function() { + debug(`Server's up on port: ${PORT}`); +}); diff --git a/test/bike-routes-test.js b/test/bike-routes-test.js new file mode 100644 index 0000000..eadeb34 --- /dev/null +++ b/test/bike-routes-test.js @@ -0,0 +1,94 @@ +'use strict'; + +const request = require('superagent'); +const expect = require('chai').expect; +// const chaiHTTP = require('chai-http'); + +require(`${__dirname}/../server.js`); + +describe('Bike Routes Module', function() { + let testBike = []; + describe('POST: 3000/api/bike', function() { + it('should post a bike to a new file', function(done) { + request.post('localhost:3000/api/bike') + .send({ brand: 'Rodriguez', type: 'Cyclocross'}) + .end((err, res) => { + if(err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.brand).to.equal('Rodriguez'); + expect(res.body.type).to.equal('Cyclocross'); + testBike = res.body; + done(); + }); + }); + it('should throw 400 error for empty post', function(done) { + request.post('localhost:3000/api/bike') + .send() + .end((err, res) => { + expect(res.status).to.equal(err.status); + expect(res.text).to.equal('BadRequestError'); + done(); + }); + }); + it('should throw 400 error wich invalid keys', function(done) { + request.post('localhost:3000/api/bike') + .send({ snow: 'man', ski: 'boot'}) + .end((err, res) => { + expect(res.status).to.equal(err.status); + expect(res.text).to.equal('BadRequestError'); + done(); + }); + }); + }); + describe('GET :3000/api/bike', function() { + // let testId = 'f8dbc3c0-fd4d-11e6-be04-3b78bdf018ba'; + it('should retun bike object and 200 status', function(done) { + request.get(`localhost:3000/api/bike/${testBike.id}`) + .end((err, res) => { + if(err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.brand).to.equal(testBike.brand); + expect(res.body.type).to.equal(testBike.type); + done(); + }); + }); + it('should return 404 not found', function(done) { + request.get('localhost:3000/api/bike/123456') + .end((err, res) => { + expect(res.status).to.equal(err.status); + expect(res.status).to.equal(404); + done(); + }); + }); + it('should return 400 bad request error', function(done) { + request.get('localhost:3000/api/bike') + .end((err, res) => { + expect(res.status).to.equal(err.status); + expect(res.status).to.equal(400); + done(); + }); + }); + }); + describe('DELETE :3000/api/bike', function() { + it('should return a 204 message with no content', function(done) { + request.delete(`localhost:3000/api/bike/${testBike.id}`) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(204); + expect(res.body).to.be.an('object'); + expect(res.body).to.be.empty; + done(); + // expect(res) + }); + }); + }); + describe('PUT :3000/api/bike', function() { + it('should return a 404 error', function(done) { + request.put('localhost:3000/api/bike') + .end((err, res) => { + expect(res.status).to.equal(404); + done(); + }); + }); + }); +});