From b98447c3bcf86e643d65f078981daf80ebfdc812 Mon Sep 17 00:00:00 2001 From: Bret Ldenburg Date: Thu, 27 Jul 2017 16:27:13 -0700 Subject: [PATCH] finished with the lab today --- .eslintrc | 21 +++ .gitignore | 136 ++++++++++++++++++ README.md | 70 ++++----- .../258e5135-b049-45e5-806d-c5d390df1dec.json | 1 + lib/parse-json.js | 32 +++++ lib/parse-url.js | 10 ++ lib/response.js | 21 +++ lib/router.js | 63 ++++++++ lib/storage.js | 40 ++++++ model/superhero.js | 12 ++ package.json | 30 ++++ route/superhero-route.js | 34 +++++ server.js | 14 ++ test/superhero-route-test.js | 67 +++++++++ 14 files changed, 519 insertions(+), 32 deletions(-) create mode 100644 .eslintrc create mode 100644 .gitignore create mode 100644 data/superhero/258e5135-b049-45e5-806d-c5d390df1dec.json create mode 100644 lib/parse-json.js create mode 100644 lib/parse-url.js create mode 100644 lib/response.js create mode 100644 lib/router.js create mode 100644 lib/storage.js create mode 100644 model/superhero.js create mode 100644 package.json create mode 100644 route/superhero-route.js create mode 100644 server.js create mode 100644 test/superhero-route-test.js 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 0aaf9f2..0852e4e 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,38 @@ -![cf](https://i.imgur.com/7v5ASc8.png) Lab 09: Vanilla REST API w/ Persistence -====== - -## 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 learn how to save resource data to the file system for a layer of data persistence -* students will learn how to refactor commonly used coding constructs into custom helper modules - -## Requirements - -#### Configuration -* `package.json` -* `.eslintrc` -* `.gitignore` -* `README.md` - * your `README.md` should include detailed instructions on how to use your API - * this should include documentation on how to access your API endpoints - -#### Feature Tasks -* continue working on your vanilla REST API -* refactor your routes to be contained in a separate module (ex: `route/resource-route.js`) -* refactor your `res` messages & status codes to be contained in a separate module (ex: `response.js`) -* refactor the `storage.js` module to use file system persistence - * use the `fs` module to create and read the associated data files - * the name of the file should contain the related resource id +#Overview + +* This RESTful API provides the back-end infrastructure and funtionality to create, read, update, and delete data relative to superheroes. + +#Architecture + +

This API is structured on a Model View Controller(MVC) architectue pattern. The basic technologies are: node.js server, node.http module, our own "express like" middleware.

+ +

Middleware:

+ +* We wrote a vanilla version of our own router that handles the base routing. + +* We wrote a vanilla version of a body-parser module that parses JSON data. + +#API endpoints + +##POST /api/superhero + +

Required Data:

+ +* Provide superhero name, the comic universe where they are from as JSON. + +

This route will create a new superhero by providing a superhero name and a comic book universe from which they reside in the body of the request.

+ +##GET /api/superhero + +

Required Data:

+ +* Provide a specific unique superhero id. + +

This route will require a unique superhero id and grab the specific JSON object associated with that id.

+ +#Testing + +* Testing Framework mocha test runner +* chai(expect) +* bluebird promise library +* eslint diff --git a/data/superhero/258e5135-b049-45e5-806d-c5d390df1dec.json b/data/superhero/258e5135-b049-45e5-806d-c5d390df1dec.json new file mode 100644 index 0000000..5da1e8f --- /dev/null +++ b/data/superhero/258e5135-b049-45e5-806d-c5d390df1dec.json @@ -0,0 +1 @@ +{"id":"258e5135-b049-45e5-806d-c5d390df1dec","name":"name","comicUni":"comicUni"} \ No newline at end of file diff --git a/lib/parse-json.js b/lib/parse-json.js new file mode 100644 index 0000000..07ebad7 --- /dev/null +++ b/lib/parse-json.js @@ -0,0 +1,32 @@ +'use strict'; + +module.exports = function(req) { + return new Promise((resolve, reject) => { + if (req.method === 'POST' || req.method === 'PUT') { + var body = ''; + + req.on('data', data => { + body += data.toString(); + }); + + req.on('end', () => { + try { + req.body = JSON.parse(body); + resolve(req); + } catch (err) { + console.error(err); + reject(err); + } + }); + + req.on('error', err => { + console.error(err); + reject(err); + }); + + return; + } + + resolve(); + }); +}; diff --git a/lib/parse-url.js b/lib/parse-url.js new file mode 100644 index 0000000..bd4e014 --- /dev/null +++ b/lib/parse-url.js @@ -0,0 +1,10 @@ +'use strict'; + +const parseUrl = require('url').parse; +const parseQuery = require('querystring').parse; + +module.exports = function(req) { + req.url = parseUrl(req.url); + req.url.query = parseQuery(req.url.query); + return Promise.resolve(req); +}; diff --git a/lib/response.js b/lib/response.js new file mode 100644 index 0000000..01f0d9f --- /dev/null +++ b/lib/response.js @@ -0,0 +1,21 @@ +'use strict'; + +module.exports = exports = {}; + +exports.sendJSON = function(res, status, data) { + res.writeHead(status, { + 'Content-Type': 'application/json' + }); + + res.write(JSON.stringify(data)); + res.end(); +}; + +exports.sendText = function(res, status, msg) { + res.writeHead(status, { + 'Content-Type': 'text/plain' + }); + + res.write(msg); + res.end(); +}; diff --git a/lib/router.js b/lib/router.js new file mode 100644 index 0000000..9191a74 --- /dev/null +++ b/lib/router.js @@ -0,0 +1,63 @@ +'use strict'; + +const parseUrl = require('./parse-url.js'); +const parseJSON = require('./parse-json.js'); + +const Router = module.exports = function() { + this.routes = { + GET: {}, + POST: {}, + PUT: {}, + DELETE: {} + }; +}; + +Router.prototype.get = function(endpoint, callback) { + this.routes.GET[endpoint] = callback; +}; + +Router.prototype.post = function(endpoint, callback) { + this.routes.POST[endpoint] = callback; +}; + +Router.prototype.put = function(endpoint, callback) { + this.routes.PUT[endpoint] = callback; +}; + +Router.prototype.delete = function(endpoint, callback) { + this.routes.DELETE[endpoint] = callback; +}; + +Router.prototype.route = function() { + return (req, res) => { + Promise.all([ + parseUrl(req), + parseJSON(req) + ]) + .then( () => { + if (typeof this.routes[req.method][req.url.pathname] === 'function') { + this.routes[req.method][req.url.pathname](req, res); + return; + } + + console.error('route not found'); + + res.writeHead(404, { + 'Content-Type': 'text/plain' + }); + + res.write('route not found'); + res.end(); + }) + .catch( err => { + console.error(err); + + res.writeHead(400, { + 'Content-Type': 'text/plain' + }); + + res.write('bad request'); + res.end(); + }); + }; +}; diff --git a/lib/storage.js b/lib/storage.js new file mode 100644 index 0000000..7ee0928 --- /dev/null +++ b/lib/storage.js @@ -0,0 +1,40 @@ +'use strict'; + +const Promise = require('bluebird'); +const fs = Promise.promisifyAll(require('fs'), {suffix: 'Prom'}); + +module.exports = exports = {}; + +exports.createItem = function(schemaName, item) { + if (!schemaName) return Promise.reject(new Error('expected schema name')); + if (!item) return Promise.reject(new Error('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) { + if (!schemaName) return Promise.reject(new Error('expected schema name')); + if (!id) return Promise.reject(new Error('expected id')); + console.log(); + + 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( err => Promise.reject(err)); +}; + +exports.deleteItem = function(schemaName, id) { + if (!schemaName) return Promise.reject(new Error('expected schema name')); + if (!id) return Promise.reject(new Error('expected id')); + + return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`); +}; diff --git a/model/superhero.js b/model/superhero.js new file mode 100644 index 0000000..c95b365 --- /dev/null +++ b/model/superhero.js @@ -0,0 +1,12 @@ +'use strict'; + +const uuidv4 = require('uuid/v4'); + +module.exports = function(name, comicUni) { + if (!name) throw new Error('expected name'); + if (!comicUni) throw new Error('expected content'); + + this.id = uuidv4(); + this.name = name; + this.comicUni = comicUni; +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..36064e6 --- /dev/null +++ b/package.json @@ -0,0 +1,30 @@ +{ + "name": "09-vanilla_api_persistence", + "version": "1.0.0", + "description": "![cf](https://i.imgur.com/7v5ASc8.png) Lab 09: Vanilla REST API w/ Persistence ======", + "main": "server.js", + "scripts": { + "test": "mocha", + "start": "node server.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/bretladenburg/09-vanilla_api_persistence.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/bretladenburg/09-vanilla_api_persistence/issues" + }, + "homepage": "https://github.com/bretladenburg/09-vanilla_api_persistence#readme", + "dependencies": { + "bluebird": "^3.5.0", + "uuid": "^3.1.0" + }, + "devDependencies": { + "chai": "^4.1.0", + "mocha": "^3.4.2", + "superagent": "^3.5.2" + } +} diff --git a/route/superhero-route.js b/route/superhero-route.js new file mode 100644 index 0000000..6f30d5f --- /dev/null +++ b/route/superhero-route.js @@ -0,0 +1,34 @@ +'use strict'; + +const storage = require('../lib/storage.js'); +const response = require('../lib/response.js'); +const Superhero = require('../model/superhero.js'); + +module.exports = function(router) { + router.get('/api/superhero', function(req, res) { + if (req.url.query.id) { + storage.fetchItem('superhero', req.url.query.id) + .then( superhero => { + response.sendJSON(res, 200, superhero); + }) + .catch( () => { + response.sendText(res, 404, 'superhero not found'); + }); + + return; + } + + response.sendText(res, 400, 'bad request'); + }); + + router.post('/api/superhero', function(req, res) { + try { + var superhero = new Superhero(req.body.name, req.body.comicUni); + storage.createItem('superhero', superhero); + response.sendJSON(res, 200, superhero); + } catch (err) { + console.error(err); + response.sendText(res, 400, 'bad request'); + } + }); +}; diff --git a/server.js b/server.js new file mode 100644 index 0000000..4dfaffd --- /dev/null +++ b/server.js @@ -0,0 +1,14 @@ +'use strict'; + +const http = require('http'); +const Router = require('./lib/router.js'); +const PORT = process.env.PORT || 3000; +const router = new Router(); + +require('./route/superhero-route.js')(router); + +const server = http.createServer(router.route()); + +server.listen(PORT, () => { + console.log('server up;', PORT); +}); diff --git a/test/superhero-route-test.js b/test/superhero-route-test.js new file mode 100644 index 0000000..57549a3 --- /dev/null +++ b/test/superhero-route-test.js @@ -0,0 +1,67 @@ +'use strict'; + +const request = require('superagent'); +const expect = require('chai').expect; +const PORT = process.env.PORT || 3000; + +require('../server.js'); + +describe('Superhero Routes', function() { + var superhero = null; + + describe('POST: /api/superhero', function() { + it('should return a superhero', function(done) { + request.post(`localhost:${PORT}/api/superhero`) + .send({name: 'name', comicUni: 'comicUni'}) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal('name'); + expect(res.body.comicUni).to.equal('comicUni'); + superhero = res.body; + done(); + }); + }); + + it('should return a bad request', function(done) { + request.post(`localhost:${PORT}/api/superhero`) + .send({viewers: '10000', conceptArt: 'comic art'}) + .end((err, res) => { + expect(res.status).to.equal(400); + expect(res.text).to.equal('bad request'); + done(); + }); + }); + }); + + describe('GET: /api/superhero', function() { + it('should return a superhero', function(done) { + request.get(`localhost:${PORT}/api/superhero?id=${superhero.id}`) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal('name'); + expect(res.body.comicUni).to.equal('comicUni'); + done(); + }); + }); + + it('should return a bad request', function(done) { + request.get(`localhost:${PORT}/api/superhero`) + .end((err, res) => { + expect(res.status).to.equal(400); + expect(res.text).to.equal('bad request'); + done(); + }); + }); + }); + + it('should return with superhero not found', function(done) { + request.get(`localhost:${PORT}/api/superhero?id=12345`) + .end((err, res) => { + expect(res.status).to.equal(404); + expect(res.text).to.equal('superhero not found'); + done(); + }); + }); +});