diff --git a/lab-jinho/.eslintrc b/lab-jinho/.eslintrc new file mode 100644 index 0000000..8dc6807 --- /dev/null +++ b/lab-jinho/.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-jinho/.gitignore b/lab-jinho/.gitignore new file mode 100644 index 0000000..86d8c9c --- /dev/null +++ b/lab-jinho/.gitignore @@ -0,0 +1,146 @@ +Skip to content +This repository +Search +Pull requests +Issues +Gist + @jmpaik + Watch 5 + Star 1 + Fork 8 codefellows/seattle-javascript-401d12 + Code Issues 0 Pull requests 0 Projects 0 Wiki Pulse Graphs +Branch: master Find file Copy pathseattle-javascript-401d12/06-tcp_servers/demo/chat-server/.gitignore +78ba337 a day ago +@bnates bnates added lecture 06 +1 contributor +RawBlameHistory +128 lines (94 sloc) 1.85 KB +# Created by https://www.gitignore.io/api/node,vim,macos,linux,windows + +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 + + + +### Vim ### +# swap +[._]*.s[a-w][a-z] +[._]s[a-w][a-z] +# session +Session.vim +# temporary +.netrwhist +*~ +# auto-generated tag files +tags + + +### 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 + + +### 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* + + +### 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 +Contact GitHub API Training Shop Blog About +© 2016 GitHub, Inc. Terms Privacy Security Status Help diff --git a/lab-jinho/README.md b/lab-jinho/README.md new file mode 100644 index 0000000..cddce26 --- /dev/null +++ b/lab-jinho/README.md @@ -0,0 +1,93 @@ +# Vanilla-REST-API +============= + +structures : +- data + - restaurant + - random item +- lib + - parse-json.js + - parse-url.js + - response.js + - router.js + - storage.js +- model + - restaurant.js +- test + - restaurant-route-test.js +- root + - server.js + - gulpfile.js + - .gitignore + - .eslintrc + - README.md + +## Getting Started +- In terminal enter : node server.js +- also you can run gulp +- for tests in terminal enter: + - gulp OR mocha + + +### Prerequisities + +- dependencies: + +``` +npm install -S node-uuid +npm install -S superagent + +``` + +- devDependencies: + +``` +npm install -D gulp-eslint +npm install -D gulp-mocha +npm install -D mocha +npm install -D gulp +npm install -D chai + +``` + +## Running + +- In your root server, type in the command **"node server.js"** in your terminal. +- OR in terminal type: gulp + + +- GET request: + ```http localhost:3000/api/restaurant?id=selectedId ``` + +- POST request: + ```http POST localhost:3000/api/restaurant restaurantname="name of restaurant" address="location address" ``` + +- DELETE request: + ```http DELETE localhost:3000/api/person?id=selectedId ``` + +## Testing: +- we have 5 tests for GET and POST requests : + - test to ensure that API returns a status code of 404 for routes that have not been registered + - tests to ensure that **/api/restaurant** endpoint responds as described for each condition below: + - GET - test 404, responds with 'not found' for valid request made with an id that was not found + - GET - test 400, responds with 'bad request' if no id was provided in the request + - GET - test 200, response body like {} for a request made with a valid id + - POST - test 400, responds with 'bad request' for if no body provided or invalid body + - POST - test 200, response body like {} for a post request with a valid body + +## Built With: + +* Nodejs +* JavaScript + +## Versioning + +Not Applicable + +## Authors + +* **BlueToad** - [Github](https://github.com/jmpaik) + +## License + +None. diff --git a/lab-jinho/gulpfile.js b/lab-jinho/gulpfile.js new file mode 100644 index 0000000..b16e376 --- /dev/null +++ b/lab-jinho/gulpfile.js @@ -0,0 +1,23 @@ +'use strict'; + +const gulp = require('gulp'); +const eslint = require('gulp-eslint'); +const mocha = require('gulp-mocha'); + +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/**'], ['lint', 'test']); +}); + +gulp.task('default', ['dev']); diff --git a/lab-jinho/lib/error-middleware.js b/lab-jinho/lib/error-middleware.js new file mode 100644 index 0000000..534d8d7 --- /dev/null +++ b/lab-jinho/lib/error-middleware.js @@ -0,0 +1,28 @@ +'use strict'; + +const createError = require('http-errors'); +const debug = require('debug')('restaurant:error-middleware'); + +module.exports = function(err, req, res, next) { + debug('error middleware'); + + console.error('msg:', err.message); + console.error('name:', err.name); + + if (err.status) { + res.status(err.status).send(err.name); + next(); + return; + } + + if (err.name === 'ValidationError') { + err = createError(400, err.message); + res.status(err.status).send(err.name); + next(); + return; + } + + err = createError(500, err.message); + res.status(err.status).send(err.name); + next(); +}; diff --git a/lab-jinho/model/list.js b/lab-jinho/model/list.js new file mode 100644 index 0000000..65a8171 --- /dev/null +++ b/lab-jinho/model/list.js @@ -0,0 +1,36 @@ +'use strict'; + +const mongoose = require('mongoose'); +const createError = require('http-errors'); +const debug = require('debug')('restaurant:list'); +const Schema = mongoose.Schema; + +const Restaurant = require('./restaurant.js'); + +const listSchema = Schema({ + name: { type: String, required: true }, + timestamp: { type: Date, required: true }, + restaurants: [{ type: Schema.Types.ObjectId, ref: 'restaurant' }] +}); + +const List = module.exports = mongoose.model('list', listSchema); + +List.findByIdAndAddRestaurant = function(id, restaurant) { + debug('findByIdAndAddRestaurant'); + + return List.findById(id) + .catch( err => Promise.reject(createError(404, err.message))) + .then( list => { + restaurant.listID = list._id; + this.tempList = list; + return new Restaurant(restaurant).save(); + }) + .then( restaurant => { + this.tempList.restaurants.push(restaurant._id); + this.tempRestaurant = restaurant; + return this.tempList.save(); + }) + .then ( () => { + return this.tempRestaurant; + }); +}; diff --git a/lab-jinho/model/restaurant.js b/lab-jinho/model/restaurant.js new file mode 100644 index 0000000..3a151eb --- /dev/null +++ b/lab-jinho/model/restaurant.js @@ -0,0 +1,12 @@ +'use strict'; + +const mongoose = require('mongoose'); +const Schema = mongoose.Schema; + +const restaurantSchema = Schema({ + restaurantname: { type: String, required: true }, + address: { type: String, required: true }, + listID: { type: Schema.Types.ObjectId, required: true } +}); + +module.exports = mongoose.model('restaurant', restaurantSchema); diff --git a/lab-jinho/package.json b/lab-jinho/package.json new file mode 100644 index 0000000..16ac0ef --- /dev/null +++ b/lab-jinho/package.json @@ -0,0 +1,33 @@ +{ + "name": "lab-jinho", + "version": "1.0.0", + "description": "", + "main": "gulpfile.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "DEBUG='restaurant*' mocha", + "start": "DEBUG='restaurant*' node server.js" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "Express": "^3.0.1", + "bluebird": "^3.4.6", + "body-parser": "^1.15.2", + "cors": "^2.8.1", + "debug": "^2.4.5", + "express": "^4.14.0", + "http-errors": "^1.5.1", + "mongoose": "^4.7.4", + "morgan": "^1.7.0", + "node-uuid": "^1.4.7" + }, + "devDependencies": { + "chai": "^3.5.0", + "mocha": "^3.2.0", + "superagent": "^3.3.0" + } +} diff --git a/lab-jinho/route/list-route.js b/lab-jinho/route/list-route.js new file mode 100644 index 0000000..db03bce --- /dev/null +++ b/lab-jinho/route/list-route.js @@ -0,0 +1,37 @@ +'use strict'; + +const Router = require('express').Router; +const jsonParser = require('body-parser').json(); +const createError = require('http-errors'); + +const List = require('../model/list.js'); +const listRouter = module.exports = new Router(); + +listRouter.post('/api/list', jsonParser, function(req, res, next) { + req.body.timestamp = new Date(); + new List(req.body).save() + .then( list => res.json(list)) + .catch(next); +}); + +listRouter.get('/api/list/:id', function(req, res, next) { + List.findById(req.params.id) + .populate('restaurants') + .then( list => res.json(list)) + .catch( err => next(createError(404, err.message))); +}); + +listRouter.put('/api/list/:id', jsonParser, function(req, res, next) { + List.findByIdAndUpdate(req.params.id, req.body, { new: true }) + .then( list => res.json(list)) + .catch( err => { + if (err.name === 'ValidationError') return next(err); + next(createError(404, err.message)); + }); +}); + +listRouter.delete('/api/list/:id', function(req, res, next) { + List.findByIdAndRemove(req.params.id) + .then( () => res.status(204).send()) + .catch( err => next(createError(404, err.message))); +}); diff --git a/lab-jinho/route/restaurant-route.js b/lab-jinho/route/restaurant-route.js new file mode 100644 index 0000000..57ff56a --- /dev/null +++ b/lab-jinho/route/restaurant-route.js @@ -0,0 +1,13 @@ +'use strict'; + +const Router = require('express').Router; +const jsonParser = require('body-parser').json(); +const List = require('../model/list.js'); + +const restaurantRouter = module.exports = new Router(); + +restaurantRouter.post('/api/list/:listID/restaurant', jsonParser, function(req, res, next) { + List.findByIdAndAddRestaurant(req.params.listID, req.body) + .then( note => res.json(note)) + .catch(next); +}); diff --git a/lab-jinho/server.js b/lab-jinho/server.js new file mode 100644 index 0000000..4ab9a63 --- /dev/null +++ b/lab-jinho/server.js @@ -0,0 +1,39 @@ +'use strict'; + +//**DEPENDENCIES** + +//npm modules +const express = require('express'); +const morgan = require('morgan'); +const mongoose = require('mongoose'); +const cors = require('cors'); +const Promise = require('bluebird'); +const debug = require('debug')('restaurant:server'); + +//app modules +const listRouter = require('./route/list-route.js'); +const restaurantRouter = require('./route/restaurant-route.js'); +const errors = require('./lib/error-middleware.js'); + +//environment variables +const PORT = process.env.PORT || 3000; +const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost/restaurant'; + +//**LOGIC** +mongoose.Promise = Promise; +mongoose.connect(MONGODB_URI); + +//middleware components app.use +const app = express(); +app.use(cors()); +app.use(morgan('dev')); + +app.use(listRouter); +app.use(restaurantRouter); +app.use(errors); + + +//**START SERVER** +app.listen(PORT, () => { + debug(`server up: ${PORT}`); +}); diff --git a/lab-jinho/test/list-route-test.js b/lab-jinho/test/list-route-test.js new file mode 100644 index 0000000..a786908 --- /dev/null +++ b/lab-jinho/test/list-route-test.js @@ -0,0 +1,127 @@ +'use strict'; + +const expect = require('chai').expect; +const request = require('superagent'); +const List = require('../model/list.js'); +const Restaurant = require('../model/restaurant.js'); + +const PORT = process.env.PORT || 3000; + +require('../server.js'); + +const url = `http://localhost:${PORT}`; + +const exampleList = { + name: 'test list', + timestamp: new Date() +}; + +const exampleRestaurant = { + restaurantname: 'test restaurant', + address: 'test address' +}; + +describe('List Routes', function() { + describe('POST: /api/list', function() { + describe('with valid body', function() { + after( done => { + if (this.tempList) { + List.remove({}) + .then( ()=> done()) + .catch(done); + return; + } + done(); + }); + + it('should return list', done => { + request.post(`${url}/api/list`) + .send(exampleList) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal('test list'); + this.tempList = res.body; + done(); + }); + }); + }); + }); + + describe('GET: /api/list/:id', function() { + describe('with valid body', function() { + before( done => { + new List(exampleList).save() + .then( list => { + this.tempList = list; + return List.findByIdAndAddRestaurant(list._id, exampleRestaurant); + }) + .then( restaurant => { + this.tempRestaurant = restaurant; + done(); + }) + .catch(done); + }); + + after( done => { + if (this.tempList) { + List.remove({}) + .then( () => done()) + .catch(done); + return; + } + done(); + }); + + it('should return list', done => { + request.get(`${url}/api/list/${this.tempList._id}`) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal('test list'); + expect(res.body.restaurants.length).to.equal(1); + expect(res.body.restaurants[0].restaurantname).to.equal(exampleRestaurant.restaurantname); + done(); + }); + }); + }); + }); + + describe('PUT: /api/list/:id', function() { + describe('with valid body', function() { + before( done => { + new List(exampleList).save() + .then( list => { + this.tempList = list; + done(); + }) + .catch(done); + }); + + after( done => { + if (this.tempList) { + List.remove({}) + .then( () => done ()) + .catch(done); + return; + } + done(); + }); + + it('should return list', done => { + var updated = { name: 'updated name' }; + + request.put(`${url}/api/list/${this.tempList._id}`) + .send(updated) + .end((err, res) => { + if (err) return done (err); + let timestamp = new Date(res.body.timestamp); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal(updated.name); + expect(timestamp.toString()).to.equal(exampleList.timestamp.toString()); + done(); + }); + }); + }); + }); +}); diff --git a/lab-jinho/test/restaurant-route-test.js b/lab-jinho/test/restaurant-route-test.js new file mode 100644 index 0000000..f260011 --- /dev/null +++ b/lab-jinho/test/restaurant-route-test.js @@ -0,0 +1,57 @@ +'use strict'; + +const expect = require('chai').expect; +const request = require('superagent'); +const List = require('../model/list.js'); +const Restaurant = require('../model/restaurant.js'); + +const PORT = process.env.PORT || 3000; + +require('../server.js'); + +const url = `http://localhost:${PORT}`; + +const exampleList = { + name: 'test list', + timestamp: new Date() +}; + +const exampleRestaurant = { + restaurantname: 'test restaurant', + address: 'test address' +}; + +describe('Restaurant Routes', function() { + describe('POST: /api/list/:listID/restaurant', function() { + describe('with valid list id and restaurant body', () => { + before( done => { + new List(exampleList).save() + .then( list => { + this.tempList = list; + done(); + }) + .catch(done); + }); + + after( done => { + Promise.all([ + List.remove({}), + Restaurant.remove({}) + ]) + .then(() => done()) + .catch(done); + }); + + it('should return restaurant', done => { + request.post(`${url}/api/list/${this.tempList.id}/restaurant`) + .send(exampleRestaurant) + .end((err, res) => { + if (err) return done(err); + expect(res.body.restaurantname).to.equal(exampleRestaurant.restaurantname); + expect(res.body.listID).to.equal(this.tempList._id.toString()); + done(); + }); + }); + }); + }); +});