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 0aaf9f2..994c94e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -![cf](https://i.imgur.com/7v5ASc8.png) Lab 09: Vanilla REST API w/ Persistence +![cf](https://i.imgur.com/7v5ASc8.png) Lab 08: Vanilla REST API ====== ## Submission Instructions @@ -10,23 +10,48 @@ * 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 +* students will learn to use promise constructs to manage asynchronous code +* students will learn to create a vanilla RESTful API with in-memory persistence ## 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 + * `.gitignore` + * `.eslintrc` + * `package.json` + * `README.md` #### 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 +* create the following directories to organize your code: + * `lib` + * `model` + * `test` +* create an HTTP server using the native NodeJS `http` module +* create an object constructor that creates a _simple resource_ with at least 3 properties + * include an `id` property that is set to a unique id (**hint:** you'll need to use `node-uuid`) + * include two additional properties of your choice (ex: name, content, etc.) +* create a custom body parser module that uses promises to parse the JSON body of `POST` and `PUT` requests +* create a custom url parser module that returns a promise and uses the NodeJS `url` and `querystring` modules to parse the request url +* create a router constructor that handles requests to `GET`, `POST`, `PUT`, and `DELETE` requests +* create a storage module that will store resources by their schema type (ex: note) and id + +## 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 + +## Bonus +* **2pts:** a `GET` request to `/api/simple-resource-name` with no **?id=** should return an array of all of the ids for that resource diff --git a/data/bake/a325357c-0dbb-4ae8-b3bd-7286de9bba24.json b/data/bake/a325357c-0dbb-4ae8-b3bd-7286de9bba24.json new file mode 100644 index 0000000..c4cc24c --- /dev/null +++ b/data/bake/a325357c-0dbb-4ae8-b3bd-7286de9bba24.json @@ -0,0 +1 @@ +{"id":"a325357c-0dbb-4ae8-b3bd-7286de9bba24","bakedGood":"muffin","description":"naked cupcake","calories":255} \ No newline at end of file diff --git a/data/bake/b935f3eb-179d-47c2-9e9a-a484b20be924.json b/data/bake/b935f3eb-179d-47c2-9e9a-a484b20be924.json new file mode 100644 index 0000000..f8dba92 --- /dev/null +++ b/data/bake/b935f3eb-179d-47c2-9e9a-a484b20be924.json @@ -0,0 +1 @@ +{"id":"b935f3eb-179d-47c2-9e9a-a484b20be924","bakedGood":"muffin","description":"naked cupcake","calories":255} \ No newline at end of file diff --git a/lib/parse-json.js b/lib/parse-json.js new file mode 100644 index 0000000..ee9b114 --- /dev/null +++ b/lib/parse-json.js @@ -0,0 +1,30 @@ +'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) { + reject(err); + } + }); + + req.on('error', err => { + reject(err); + }); + + return; + } + + resolve(); + }); +}; \ No newline at end of file diff --git a/lib/parse-url.js b/lib/parse-url.js new file mode 100644 index 0000000..c4b34ac --- /dev/null +++ b/lib/parse-url.js @@ -0,0 +1,11 @@ +'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); +}; \ No newline at end of file diff --git a/lib/response.js b/lib/response.js new file mode 100644 index 0000000..e475dae --- /dev/null +++ b/lib/response.js @@ -0,0 +1,15 @@ +'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(); +}; \ No newline at end of file diff --git a/lib/router.js b/lib/router.js new file mode 100644 index 0000000..e162abd --- /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; + } + + 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..59cbce1 --- /dev/null +++ b/lib/storage.js @@ -0,0 +1,41 @@ +'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( () => 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..82269f8 --- /dev/null +++ b/model/bake.js @@ -0,0 +1,14 @@ +'use strict'; + +const uuidv4 = require('uuid/v4'); + +module.exports = function(bakedGood, description, calories) { + if (!bakedGood) throw new Error('expected baked good'); + if (!description) throw new Error('expected description'); + if (!calories) throw new Error('expected calories'); + + this.id = uuidv4(); + this.bakedGood = bakedGood; + this.description = description; + this.calories = calories; +}; \ No newline at end of file diff --git a/npm-debug.log b/npm-debug.log new file mode 100644 index 0000000..94eb97f --- /dev/null +++ b/npm-debug.log @@ -0,0 +1,48 @@ +0 info it worked if it ends with ok +1 verbose cli [ '/Users/devjonah/.nvm/versions/node/v6.11.1/bin/node', +1 verbose cli '/Users/devjonah/.nvm/versions/node/v6.11.1/bin/npm', +1 verbose cli 'run', +1 verbose cli 'test' ] +2 info using npm@3.10.10 +3 info using node@v6.11.1 +4 verbose run-script [ 'pretest', 'test', 'posttest' ] +5 info lifecycle 08-vanilla_rest_api@1.0.0~pretest: 08-vanilla_rest_api@1.0.0 +6 silly lifecycle 08-vanilla_rest_api@1.0.0~pretest: no script for pretest, continuing +7 info lifecycle 08-vanilla_rest_api@1.0.0~test: 08-vanilla_rest_api@1.0.0 +8 verbose lifecycle 08-vanilla_rest_api@1.0.0~test: unsafe-perm in lifecycle true +9 verbose lifecycle 08-vanilla_rest_api@1.0.0~test: PATH: /Users/devjonah/.nvm/versions/node/v6.11.1/lib/node_modules/npm/bin/node-gyp-bin:/Users/devjonah/codefellows/401/labs/09-vanilla_api_persistence/node_modules/.bin:/Users/devjonah/.nvm/versions/node/v6.11.1/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/git/bin +10 verbose lifecycle 08-vanilla_rest_api@1.0.0~test: CWD: /Users/devjonah/codefellows/401/labs/09-vanilla_api_persistence +11 silly lifecycle 08-vanilla_rest_api@1.0.0~test: Args: [ '-c', 'mocha' ] +12 silly lifecycle 08-vanilla_rest_api@1.0.0~test: Returned: code: 1 signal: null +13 info lifecycle 08-vanilla_rest_api@1.0.0~test: Failed to exec test script +14 verbose stack Error: 08-vanilla_rest_api@1.0.0 test: `mocha` +14 verbose stack Exit status 1 +14 verbose stack at EventEmitter. (/Users/devjonah/.nvm/versions/node/v6.11.1/lib/node_modules/npm/lib/utils/lifecycle.js:255:16) +14 verbose stack at emitTwo (events.js:106:13) +14 verbose stack at EventEmitter.emit (events.js:191:7) +14 verbose stack at ChildProcess. (/Users/devjonah/.nvm/versions/node/v6.11.1/lib/node_modules/npm/lib/utils/spawn.js:40:14) +14 verbose stack at emitTwo (events.js:106:13) +14 verbose stack at ChildProcess.emit (events.js:191:7) +14 verbose stack at maybeClose (internal/child_process.js:891:16) +14 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5) +15 verbose pkgid 08-vanilla_rest_api@1.0.0 +16 verbose cwd /Users/devjonah/codefellows/401/labs/09-vanilla_api_persistence +17 error Darwin 16.6.0 +18 error argv "/Users/devjonah/.nvm/versions/node/v6.11.1/bin/node" "/Users/devjonah/.nvm/versions/node/v6.11.1/bin/npm" "run" "test" +19 error node v6.11.1 +20 error npm v3.10.10 +21 error code ELIFECYCLE +22 error 08-vanilla_rest_api@1.0.0 test: `mocha` +22 error Exit status 1 +23 error Failed at the 08-vanilla_rest_api@1.0.0 test script 'mocha'. +23 error Make sure you have the latest version of node.js and npm installed. +23 error If you do, this is most likely a problem with the 08-vanilla_rest_api package, +23 error not with npm itself. +23 error Tell the author that this fails on your system: +23 error mocha +23 error You can get information on how to open an issue for this project with: +23 error npm bugs 08-vanilla_rest_api +23 error Or if that isn't available, you can get their info via: +23 error npm owner ls 08-vanilla_rest_api +23 error There is likely additional logging output above. +24 verbose exit [ 1, true ] diff --git a/package.json b/package.json new file mode 100644 index 0000000..cf4d5c9 --- /dev/null +++ b/package.json @@ -0,0 +1,34 @@ +{ + "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/ohjonah/08-vanilla_rest_api.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/ohjonah/08-vanilla_rest_api/issues" + }, + "homepage": "https://github.com/ohjonah/08-vanilla_rest_api#readme", + "devDependencies": { + "cha": "^0.2.1", + "chai": "^4.1.0", + "mocha": "^3.4.2", + "superagent": "^3.5.2" + }, + "dependencies": { + "bluebird": "^3.5.0", + "uuid": "^3.1.0" + } +} diff --git a/route/bake-route.js b/route/bake-route.js new file mode 100644 index 0000000..9e80d47 --- /dev/null +++ b/route/bake-route.js @@ -0,0 +1,52 @@ +'use strict'; + +const storage = require('../lib/storage.js'); +const response = require('../lib/response.js'); +const Note = require('../model/bake.js'); + +module.exports = function(router) { + router.get('/api/bake', function(req, res) { + if (req.url.query.id) { + storage.fetchItem('bake', req.url.query.id) + .then( bake => { + response.sendJSON(res, 200, bake); + }) + // error block + .catch( () => { + response.sendText(res, 404, 'not found'); + }); + + return; + } + response.sendText(res, 400, 'bad request'); + }); + + router.post('/api/bake', function(req, res) { + try { + var note = new Note(req.body.bakedGood, req.body.description, req.body.calories); + + storage.createItem('bake', note); + + response.sendJSON(res, 200, note); + } catch (err) { + response.sendText(res, 400, 'bad request'); + } + }); + + router.delete('/api/bake', function(req, res) { + if (req.url.query.id) { + storage.deleteItem('bake', req.url.query.id) + .then( () => { + response.sendText(res, 204, 'deleted'); + }) + .catch( err => { + console.error(err); + response.sendText(res, 400, 'bad request'); + }); + + return; + } + + response.sendText(res, 400, 'bad request'); + }); +}; diff --git a/server.js b/server.js new file mode 100644 index 0000000..650e296 --- /dev/null +++ b/server.js @@ -0,0 +1,13 @@ +'use strict'; + +const http = require('http'); +const Router = require('./lib/router.js'); +const PORT = process.env.PORT || 3000; +const router = new Router(); +require('./route/bake-route.js')(router); + +const server = http.createServer(router.route()); + +server.listen(PORT, () => { + console.log(`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..4cfd248 --- /dev/null +++ b/test/bake-route-test.js @@ -0,0 +1,87 @@ +'use strict'; + +const request = require('superagent'); +const expect = require('chai').expect; + +require('../server.js'); + +describe('Baked Good Routes', function() { + var bake = null; + + 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', function(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