diff --git a/lab-hawa/.eslintrc b/lab-hawa/.eslintrc new file mode 100644 index 0000000..8dc6807 --- /dev/null +++ b/lab-hawa/.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/lab-hawa/.gitignore b/lab-hawa/.gitignore new file mode 100644 index 0000000..43bce2d --- /dev/null +++ b/lab-hawa/.gitignore @@ -0,0 +1,117 @@ +# Created by https://www.gitignore.io/api/ma,node,macos,windows,linux + +#!! ERROR: ma is undefined. Use list command to see defined gitignore types !!# + +node_modules/ + +### Node ### +# Logs +logs +*.log +npm-debug.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 + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules +jspm_packages + +# 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 + + + +### 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 + + +### Windows ### +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* diff --git a/lab-hawa/README.md b/lab-hawa/README.md new file mode 100644 index 0000000..e7334f4 --- /dev/null +++ b/lab-hawa/README.md @@ -0,0 +1,119 @@ +__Single Resource Express API__ +====== +This server-side application creates a single resource REST API implementing [Express.js](http://expressjs.com/) which allows the user to POST, GET and DELETE requests via the terminal. + +--- +## Cloning the Repository +Clone down this repository: https://github.com/abdih17/11-express_single_resource_api.git + +``` +$ git clone https://github.com/abdih17/11-express_single_resource_api.git +``` + +## Installation + +Install any dependency from the `package.json` file into the project root +directory, and start the server. + +```sh +$ cd lab-hawa +$ npm i +$ npm start +``` + +You should receive the following result: `Server up: 3000` or whichever port number have preset in your environment variables. + +## Set Up Necessary Directories + +Before writing our POST requests in our server, we need to create a directory were the data can be stored. In order to do so, you need to create a folder called 'spiritAnimal', inside of a folder called 'data' + +```sh +$ cd lab-hawa +$ mkdir data +$ cd data +$ mkdir spiritAnimal +``` + +## POST, GET, and DELETE Requests + +**POST Request:** +The POST request must include name, spiritAnimal, and spiritAnimalName parameters. + +>**In an new terminal window, send a POST request by using the command:** +>`http POST localhost:3000/api/spiritAnimal name= spiritAnimal= spiritAnimalName=`. + +A successful response should return a JSON object with values you entered along with a unique **id number** and a status code of **200**. This will also create a new `.json` file into the `data` folder with the `id` as the file name. + +Here's an example of a POST request and the successful response: +``` +$ http POST localhost:3000/api/spiritAnimal name="Hawa" spiritAnimal="Pink Dragon" spiritAnimalName="Simba" + +HTTP/1.1 200 OK +Connection: keep-alive +Content-Length: 115 +Content-Type: application/json; charset=utf-8 +Date: Tue, 20 Dec 2016 18:10:12 GMT +ETag: W/"73-9UbvR26KBJnG17ThN4YOOg" +X-Powered-By: Express + +{ + "id": "8cd78500-c6df-11e6-aae4-8d9fefc8cd83", + "name": "Hawa", + "spiritAnimal": "Pink Dragon", + "spiritAnimalName": "Simba" +} +``` + +**GET Request:** + +>**In a new terminal window, send a `GET` request by using the command:** +>`http localhost:3000/api/spiritAnimal?id=`. + +A successful response should return a JSON object with a status of **200**. + +Using the unique **id** number from, here's an example of a successful GET request and response: +``` +$ http localhost:3000/api/spiritAnimal?id=8cd78500-c6df-11e6-aae4-8d9fefc8cd83 + +HTTP/1.1 200 OK +Connection: keep-alive +Content-Length: 115 +Content-Type: application/json; charset=utf-8 +Date: Tue, 20 Dec 2016 18:13:52 GMT +ETag: W/"73-CYiHeGR1flyV0Ocsh21Z9w" +X-Powered-By: Express + +{ + "id": "8cd78500-c6df-11e6-aae4-8d9fefc8cd83", + "name": "Hawa", + "spiritAnimal": "Pink Dragon", + "spiritAnimalName": "Simba" +} + +``` + +**DELETE Request:** + +>**In a new terminal window, send a `DELETE` request by using the command:** +>`http DELETE localhost:8000/api/spiritAnimal?id=` + +The a successful response should return a **204** status code with no content. +Here's a successful DELETE request and response (which returns no content): +``` +$ http DELETE localhost:3000/api/spiritAnimal?id=8cd78500-c6df-11e6-aae4-8d9fefc8cd83 + +HTTP/1.1 204 No Content +Connection: keep-alive +Date: Tue, 20 Dec 2016 18:25:21 GMT +ETag: W/"0-1B2M2Y8AsgTpgAmY7PhCfg" +X-Powered-By: Express + + + +``` + +## Exit the Server + +Go back to the terminal where your server is running with the port number and press **Ctrl+C** in order to exit the server. + +--- diff --git a/lab-hawa/data/spiritAnimal/045b6010-c6e0-11e6-a21f-8f6373b2c0e4.json b/lab-hawa/data/spiritAnimal/045b6010-c6e0-11e6-a21f-8f6373b2c0e4.json new file mode 100644 index 0000000..b650ad9 --- /dev/null +++ b/lab-hawa/data/spiritAnimal/045b6010-c6e0-11e6-a21f-8f6373b2c0e4.json @@ -0,0 +1 @@ +{"id":"045b6010-c6e0-11e6-a21f-8f6373b2c0e4","name":"Hawa","spiritAnimal":"Pink Dragon","spiritAnimalName":"Simba"} \ No newline at end of file diff --git a/lab-hawa/data/spiritAnimal/677dcb10-c6e0-11e6-a21f-8f6373b2c0e4.json b/lab-hawa/data/spiritAnimal/677dcb10-c6e0-11e6-a21f-8f6373b2c0e4.json new file mode 100644 index 0000000..f446ef9 --- /dev/null +++ b/lab-hawa/data/spiritAnimal/677dcb10-c6e0-11e6-a21f-8f6373b2c0e4.json @@ -0,0 +1 @@ +{"id":"677dcb10-c6e0-11e6-a21f-8f6373b2c0e4","name":"Harry Potter","spiritAnimal":"Hippogriff","spiritAnimalName":"Hippogriff The 3rd"} \ No newline at end of file diff --git a/lab-hawa/data/spiritAnimal/74c02f10-fd28-11e6-97de-077823d073bd.json b/lab-hawa/data/spiritAnimal/74c02f10-fd28-11e6-97de-077823d073bd.json new file mode 100644 index 0000000..131da3c --- /dev/null +++ b/lab-hawa/data/spiritAnimal/74c02f10-fd28-11e6-97de-077823d073bd.json @@ -0,0 +1 @@ +{"id":"74c02f10-fd28-11e6-97de-077823d073bd","name":"Hawa","spiritAnimal":"pink dragon","spiritAnimalName":"Simba"} \ No newline at end of file diff --git a/lab-hawa/data/spiritAnimal/9acf39d0-fd28-11e6-bf1b-1b6f5f187e5c.json b/lab-hawa/data/spiritAnimal/9acf39d0-fd28-11e6-bf1b-1b6f5f187e5c.json new file mode 100644 index 0000000..c0df5b9 --- /dev/null +++ b/lab-hawa/data/spiritAnimal/9acf39d0-fd28-11e6-bf1b-1b6f5f187e5c.json @@ -0,0 +1 @@ +{"id":"9acf39d0-fd28-11e6-bf1b-1b6f5f187e5c","name":"Hawa","spiritAnimal":"pink dragon","spiritAnimalName":"Simba"} \ No newline at end of file diff --git a/lab-hawa/gulpfile.js b/lab-hawa/gulpfile.js new file mode 100644 index 0000000..00fd57d --- /dev/null +++ b/lab-hawa/gulpfile.js @@ -0,0 +1,25 @@ +'use strict'; + +const gulp = require('gulp'); +const eslint = require('gulp-eslint'); +const mocha = require('gulp-mocha'); + +//TODO:watch each individual file?? + +gulp.task('test', function(){ + gulp.src('./test/*-test.js', {read: false}) + .pipe(mocha({reporter: 'spec'})); +}); + +gulp.task('lint', function(){ + return gulp.src(['**/*.js','!node_modules/**']) + .pipe(eslint()) + .pipe(eslint.format()) + .pipe(eslint.failAfterError()); +}); + +gulp.task('dev', function(){ + gulp.watch(['**/*.js','!node_modules/**'], ['test', 'lint']); +}); + +gulp.task('default', ['dev']); diff --git a/lab-hawa/lib/storage.js b/lab-hawa/lib/storage.js new file mode 100644 index 0000000..6bccba4 --- /dev/null +++ b/lab-hawa/lib/storage.js @@ -0,0 +1,46 @@ +'use strict'; + +const Promise = require('bluebird'); +const fs = Promise.promisifyAll(require('fs'), {suffix: 'Prom'}); +const createError = require('http-errors'); +const debug = require('debug')('spiritAnimal:storage'); + +module.exports = exports = {}; + +exports.createItem = function(schemaName, item) { + debug('createItem -- storage.js'); + + 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 -- storage.js'); + + 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 => { + let item = JSON.parse(data.toString()); + return item; + }) + .catch( err => Promise.reject(createError(404, err.message))); +}; + +exports.deleteItem = function(schemaName, id) { + debug('deleteItem -- storage.js'); + + if(!schemaName) return Promise.reject(new Error('expected schema name')); + if (!id) return Promise.reject(createError(400, 'expected id')); + + return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`) + .then(() => Promise.resolve()) + .catch(err => Promise.reject(createError(404, err.message))); +}; diff --git a/lab-hawa/model/spiritAnimal.js b/lab-hawa/model/spiritAnimal.js new file mode 100644 index 0000000..8380568 --- /dev/null +++ b/lab-hawa/model/spiritAnimal.js @@ -0,0 +1,43 @@ +'use strict'; + +const uuid = require('node-uuid'); +const createError = require('http-errors'); +const debug = require('debug')('spiritAnimal:spiritAnimal'); +const storage = require('../lib/storage.js'); + +const SpiritAnimal = module.exports = function(name, spiritAnimal, spiritAnimalName) { + debug('spirit animal constructor'); + + if (!name) throw createError(400, 'expected name'); + if (!spiritAnimal) throw createError(400, 'expected spirit animal'); + if (!spiritAnimalName) throw createError(400, 'expected favorite animal'); + + this.id = uuid.v1(); + this.name = name; + this.spiritAnimal = spiritAnimal; + this.spiritAnimalName = spiritAnimalName; +}; +//this is a wrapper method. Static = not instantiated on the object. If we console log 'this', +//we get back a constructor averse a the properties of a constructor. +SpiritAnimal.createSpiritAnimal = function (_spiritAnimal) { + debug('createItem -- spiritAnimal.js'); + + try { + let spiritAnimal = new SpiritAnimal(_spiritAnimal.name, _spiritAnimal.spiritAnimal, _spiritAnimal.spiritAnimalName); + return storage.createItem('spiritAnimal', spiritAnimal); + } catch (err) { + return Promise.reject(err); + } +}; + +SpiritAnimal.fetchSpiritAnimal = function(id) { + debug('fetchSpiritAnimal'); + + return storage.fetchItem('spiritAnimal', id); +}; + +SpiritAnimal.deleteSpiritAnimal = function(id) { + debug('deleteSpiritAnimal'); + + return storage.deleteItem('spiritAnimal', id); +}; diff --git a/lab-hawa/package.json b/lab-hawa/package.json new file mode 100644 index 0000000..4f4193c --- /dev/null +++ b/lab-hawa/package.json @@ -0,0 +1,24 @@ +{ + "name": "lab-hawa", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "start": "DEBUG='spiritAnimal*' node server.js" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "bluebird": "^3.4.6", + "body-parser": "^1.15.2", + "chai": "^3.5.0", + "debug": "^2.4.5", + "express": "^4.14.0", + "http-errors": "^1.5.1", + "morgan": "^1.7.0", + "node-uuid": "^1.4.7", + "superagent": "^3.3.1" + } +} diff --git a/lab-hawa/server.js b/lab-hawa/server.js new file mode 100644 index 0000000..b756e8b --- /dev/null +++ b/lab-hawa/server.js @@ -0,0 +1,59 @@ +'use strict'; + +const express = require('express'); +const morgan = require('morgan'); +const createError = require('http-errors'); +const jsonParser = require('body-parser').json(); +const debug = require('debug')('spiritAnimal:server'); +const app = express(); +const SpiritAnimal = require('./model/spiritAnimal.js'); +const PORT = process.env.PORT || 3000; + +app.use(morgan('dev')); + +app.get('/test', function(req, res) { + debug('GET: /test'); + res.json({ msg: 'test route worked' }); +}); + +app.post('/api/spiritAnimal', jsonParser, function(req, res, next) { + debug('POST: /api/spiritAnimal'); + //TODO: build POST route + SpiritAnimal.createSpiritAnimal(req.body) + .then( spiritAnimal => res.json(spiritAnimal)) + .catch( err => next(err)); +}); + +app.get('/api/spiritAnimal/:id', function(req, res, next) { + debug('GET: /api/spiritAnimal/:id'); + + SpiritAnimal.fetchSpiritAnimal(req.params.id) + .then( spiritAnimal => res.json(spiritAnimal)) + .catch( err => next(err)); +}); + +app.delete('/api/spiritAnimal/:id', function(req, res, next) { + debug('DELETE: /api/spiritAnimal'); + + SpiritAnimal.deleteSpiritAnimal(req.params.id) + .then( () => res.status(204).send('')) + .catch( err => next(err)); +}); + +app.use(function(err, req, res, next) { + debug('error middleware'); + console.error(err.message); + + if (err.status) { + res.status(err.status).send(err.name); + return; + } + + err = createError(500, err.message); + res.status(err.status).send(err.name); +}); + + +app.listen(PORT, () => { + console.log(`server up: ${PORT}`); +}); diff --git a/lab-hawa/test/spiritAnimal-test.js b/lab-hawa/test/spiritAnimal-test.js new file mode 100644 index 0000000..f1c1664 --- /dev/null +++ b/lab-hawa/test/spiritAnimal-test.js @@ -0,0 +1,86 @@ +'use strict'; + +const request = require('superagent'); +const expect = require('chai').expect; + +require('../server.js'); + +describe('Spirit Animal Routes', function() { + var spiritAnimal = null; + + describe('POST: /api/spiritAnimal', function() { + it('should return a spirit animal, and a name', function(done) { + request.post('localhost:3000/api/spiritAnimal') + .send({ name: 'Hawa', spiritAnimal: 'pink dragon', spiritAnimalName: 'Simba'}) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal('Hawa'); + expect(res.body.spiritAnimal).to.equal('pink dragon'); + expect(res.body.spiritAnimalName).to.equal('Simba'); + spiritAnimal = res.body; + done(); + }); + }); + + it('Should return a status of 400 and bad request with no body', done => { + request + .post('localhost:3000/api/spiritAnimal') + .end((err, res) => { + expect(err).to.be.an('error'); + expect(res.status).to.equal(400); + expect(res.body.id).to.equal(undefined); + done(); + }); + }); + + it('Should return a status of 400 and bad request with wrong body inputs', done => { + request + .post('localhost:3000/api/spiritAnimal') + .send({hello: 'World', world: 'Hello'}) + .end((err, res) => { + expect(err).to.be.an('error'); + expect(res.status).to.equal(400); + expect(res.body.id).to.equal(undefined); + done(); + }); + }); + }); + + describe('GET: /api/spiritAnimal', function() { + it('should return a spirit animal', function(done) { + request.get(`localhost:3000/api/spiritAnimal/${spiritAnimal.id}`) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal('Hawa'); + expect(res.body.spiritAnimal).to.equal('pink dragon'); + expect(res.body.spiritAnimalName).to.equal('Simba'); + done(); + }); + }); + + it('Should return 404 not found for a good request, but wrong ID', done => { + request + .get('localhost:3000/api/spiritAnimal?id=22') + .end((err, res) => { + expect(err).to.be.an('error'); + expect(res.status).to.equal(404); + expect(res.body.name).to.equal(undefined); + done(); + }); + }); + }); + + describe('DELETE: /api/spiritAnimal', function() { + it('should return no content', function(done) { + request.delete(`localhost:3000/api/spiritAnimal/${spiritAnimal.id}`) + .end((err, res) => { + expect(res.status).to.equal(204); + expect(res.body.title).to.equal(undefined); + expect(res.body.skill).to.equal(undefined); + done(); + }); + }); + }); +});