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 0aaf9f2..051bd82 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,75 @@ -![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 +# 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/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..d6af25a --- /dev/null +++ b/lib/response.js @@ -0,0 +1,20 @@ +'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..07167d8 --- /dev/null +++ b/lib/router.js @@ -0,0 +1,59 @@ +'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( () => { + console.log(req.method, req.url.pathname); + 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..75d5bfd --- /dev/null +++ b/lib/storage.js @@ -0,0 +1,48 @@ +'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')); + + 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`) + .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..270c39f --- /dev/null +++ b/model/beer.js @@ -0,0 +1,14 @@ +'use strict'; + +const uuidv4 = require('uuid/v4'); + +module.exports = function(name, style, IBU) { + if (!name) throw new Error('expected name'); + 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; +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..4a41dc9 --- /dev/null +++ b/package.json @@ -0,0 +1,33 @@ +{ + "name": "08-vanilla_rest_api", + "version": "1.0.0", + "description": "![cf](https://i.imgur.com/7v5ASc8.png) Lab 08: Vanilla REST API ======", + "main": "server.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "mocha", + "start": "node server.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Jamesbillard12/08-vanilla_rest_api.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/Jamesbillard12/08-vanilla_rest_api/issues" + }, + "homepage": "https://github.com/Jamesbillard12/08-vanilla_rest_api#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/beer-route.js b/route/beer-route.js new file mode 100644 index 0000000..ed493be --- /dev/null +++ b/route/beer-route.js @@ -0,0 +1,49 @@ +'use strict'; + +const storage = require('../lib/storage.js'); +const response = require('../lib/response.js'); +const Beer = require('../model/beer.js'); + +module.exports = function(router) { + router.get('/api/beer', function(req,res){ + if(req.url.query.id) { + storage.fetchItem('beer', req.url.query.id) + .then (beer => { + + response.sendJSON(res, 200, beer); + }) + .catch( err => { + console.error(err); + response.sendText(res, 404, 'not found'); + }); + return; + } + response.sendText(res, 400, 'bad request'); + }); + router.post('/api/beer', function(req, res){ + try { + var beer = new Beer(req.body.name, req.body.style, req.body.IBU); + + storage.createItem('beer', beer); + response.sendJSON(res, 200, beer); + } catch (err){ + console.error(err); + response.sendText(res, 400, 'bad request'); + } + }); + + router.delete('/api/beer', function(req, res){ + if (req.url.query.id) { + storage.deleteItem('beer', req.url.query.id) + .then( () => { + response.sendText(res, 204, 'beer deleted'); + }) + .catch( err => { + console.error(err); + response.sendText(res, 404, 'beer not found'); + }); + return; + } + response.sendText(res, 400, 'bad request'); + }); +}; diff --git a/server.js b/server.js new file mode 100644 index 0000000..ef0c7e3 --- /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/beer-route.js')(router); + +const server = http.createServer(router.route()); + +server.listen(PORT, () => { + console.log('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(); + }); + }); + }); +});