diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..f5a011f Binary files /dev/null and b/.DS_Store differ 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/cors-middleware.js b/lab-jinho/lib/cors-middleware.js new file mode 100644 index 0000000..6661797 --- /dev/null +++ b/lab-jinho/lib/cors-middleware.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function(req, res, next) { + res.append('Access-Control-Allow-Origin', '*'); + res.append('Access-Control-Allow-Headers', '*'); + next(); +}; diff --git a/lab-jinho/lib/error-middleware.js b/lab-jinho/lib/error-middleware.js new file mode 100644 index 0000000..96a627a --- /dev/null +++ b/lab-jinho/lib/error-middleware.js @@ -0,0 +1,21 @@ +'use strict'; + +const createError = require('http-errors'); +const debug = require('debug')('restaurant:error-middleware'); + +module.exports = function(err, req, res, next) { + console.error(err.message); + + if (err.status) { + debug('user error'); + + res.status(err.status).send(err.name); + next(); + return; + } + + debug('server error'); + err = createError(500, err.message); + res.status(err.status).send(err.name); + next(); +}; diff --git a/lab-jinho/lib/storage.js b/lab-jinho/lib/storage.js new file mode 100644 index 0000000..952e6fd --- /dev/null +++ b/lab-jinho/lib/storage.js @@ -0,0 +1,54 @@ +'use strict'; + +const Promise = require('bluebird'); +const fs = Promise.promisifyAll(require('fs'), {suffix: 'Prom'}); +const createError = require('http-errors'); +const debug = require('debug')('restaurant:storage'); + +module.exports = exports = {}; + +exports.createItem = function(schemaName, item) { + debug('createItem'); + + if (!schemaName) return Promise.reject(createError(400, 'expected schemaName')); + 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'); + + 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 => { + try { + let item = JSON.parse(data.toString()); + return item; + } catch (err) { + return Promise.reject(createError(500, err.message)); + } + }) + .catch(err => Promise.reject(createError(404, err.message))); +}; + +exports.deleteItem = function(schemaName, id){ + debug('deleteItem'); + + if (!schemaName) return Promise.reject(createError(400, 'expected schema name')); + if (!id) return Promise.reject(createError(400, 'expected id')); + + return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`) + .catch( err => Promise.reject(createError(404, err.message))); +}; + +exports.availIDs = function(schemaName) { + return fs.readdirProm(`${__dirname}/../data/${schemaName}`) + .then( files => files.map(restaurantname => restaurantname.split('.json')[0])) + .catch( err => Promise.reject(createError(404, err.message))); +}; diff --git a/lab-jinho/model/restaurant.js b/lab-jinho/model/restaurant.js new file mode 100644 index 0000000..4b4463a --- /dev/null +++ b/lab-jinho/model/restaurant.js @@ -0,0 +1,57 @@ +'use strict'; + +const uuid = require('node-uuid'); +const createError = require('http-errors'); +const debug = require('debug')('restaurant:restaurant'); +const storage = require('../lib/storage.js'); + +const Restaurant = module.exports = function(restaurantname, address) { + debug('restaurant constructor'); + + if (!restaurantname) throw createError(400, 'expected restaurant name'); + if (!address) throw createError(400, 'expected address'); + + this.id = uuid.v1(); + this.restaurantname = restaurantname; + this.address = address; +}; + +Restaurant.createRestaurant = function(_restaurant) { + debug('createRestaurant'); + + try { + let restaurant = new Restaurant(_restaurant.restaurantname, _restaurant.address); + return storage.createItem('restaurant', restaurant); + } catch (err) { + return Promise.reject(createError(400, err.message)); + } +}; + +Restaurant.fetchRestaurant = function(id) { + debug('fetchRestaurant'); + return storage.fetchItem('restaurant', id); +}; + +Restaurant.updateRestaurant = function(id, _restaurant) { + debug('updateRestaurant'); + + return storage.fetchItem('restaurant', id) + .catch(err => Promise.reject(createError(404, err.message))) + .then( restaurant => { + for (var prop in restaurant) { + if (prop === 'id') continue; + if (_restaurant[prop]) restaurant[prop] = _restaurant[prop]; + } + return storage.createItem('restaurant', restaurant); + }); +}; + +Restaurant.deleteRestaurant = function(id) { + debug('deleteRestaurant'); + return storage.deleteItem('restaurant', id); +}; + +Restaurant.fetchIDs = function() { + debug('fetchIDs'); + return storage.availIDs('restaurant'); +}; diff --git a/lab-jinho/package.json b/lab-jinho/package.json new file mode 100644 index 0000000..0bd6c38 --- /dev/null +++ b/lab-jinho/package.json @@ -0,0 +1,31 @@ +{ + "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", + "debug": "^2.4.5", + "express": "^4.14.0", + "http-errors": "^1.5.1", + "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/restaurant-router.js b/lab-jinho/route/restaurant-router.js new file mode 100644 index 0000000..c8449d2 --- /dev/null +++ b/lab-jinho/route/restaurant-router.js @@ -0,0 +1,43 @@ +'use strict'; + +const Router = require('express').Router; +const jsonParser = require('body-parser').json(); +const debug = require('debug')('restaurant:restaurant-router'); +const Restaurant = require('../model/restaurant.js'); +const restaurantRouter = new Router(); + +restaurantRouter.post('/api/restaurant', jsonParser, function(req, res, next) { + debug('POST: /api/restaurant'); + + Restaurant.createRestaurant(req.body) + .then( restaurant => res.json(restaurant)) + .catch( err => next(err)); +}); + +restaurantRouter.get('/api/restaurant/:id', function(req, res, next) { + debug('GET: /api/restaurant/:id'); + + Restaurant.fetchRestaurant(req.params.id) + .then( restaurant => res.json(restaurant)) + .catch( err => next(err)); +}); + +restaurantRouter.get('/api/restaurant', function(req, res, next) { + debug('GET: /api/restaurant'); + + Restaurant.fetchIDs() + .then( ids => res.json(ids)) + .catch(next); +}); + +restaurantRouter.put('/api/restaurant', jsonParser, function(req, res, next) { + debug('PUT: /api/restaurant'); + + Restaurant.updateRestaurant(req.query.id, req.body) + .then( restaurant => res.json(restaurant)) + .catch(next); +}); + + + +module.exports = restaurantRouter; diff --git a/lab-jinho/server.js b/lab-jinho/server.js new file mode 100644 index 0000000..48856fe --- /dev/null +++ b/lab-jinho/server.js @@ -0,0 +1,32 @@ +'use strict'; + +//**DEPENDENCIES** +//node modules +const express = require('express'); +const morgan = require('morgan'); +const createError = require('http-errors'); +const debug = require('debug')('restaurant:server'); +const cors = require('./lib/cors-middleware.js'); +const errors = require('./lib/error-middleware.js'); +const restaurantRouter = require('./route/restaurant-router.js'); +//npm modules + +//custom modules + + +//environment variables +const PORT = process.env.PORT || 3000; +const app = express(); +//module constants + + + +//**START SERVER** +app.use(morgan('dev')); +app.use(cors); +app.use(errors); +app.use(restaurantRouter); + +app.listen(PORT, () => { + console.log(`server up: ${PORT}`); +}); diff --git a/lab-jinho/test/restaurant-route-test.js b/lab-jinho/test/restaurant-route-test.js new file mode 100644 index 0000000..06e1bf7 --- /dev/null +++ b/lab-jinho/test/restaurant-route-test.js @@ -0,0 +1,118 @@ +'use strict'; + +const request = require('superagent'); +const expect = require('chai').expect; +const Restaurant = require('../model/restaurant.js'); +const url = 'http://localhost:3000'; + +require('../server.js'); + +const exampleRestaurant = { + restaurantname: 'red robin', + address: 'seattle, wa' +}; + +describe('Restaurant Routes', function() { + + describe('GET: /api/restaurant', function() { + describe('with a valid id', function() { + before( done => { + Restaurant.createRestaurant(exampleRestaurant) + .then(restaurant => { + this.tempRestaurant = restaurant; + done(); + }) + .catch( err => done(err)); + }); + + after( done => { + Restaurant.deleteRestaurant(this.tempRestaurant.id) + .then( ()=> done()) + .catch( err => done(err)); + }); + + it('should return restaurant', done => { + request.get(`${url}/api/restaurant/${this.tempRestaurant.id}`) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.id).to.equal(this.tempRestaurant.id); + expect(res.body.restaurantname).to.equal(this.tempRestaurant.restaurantname); + expect(res.body.address).to.equal(this.tempRestaurant.address); + done(); + }); + }); + + describe('with invalid id', function() { + it('should respond with 404 status code', done => { + request.get(`${url}/api/restaurant/123`) + .end((err, res) => { + expect(res.status).to.equal(404); + done(); + }); + }); + }); + }); + }); + + describe('POST: /api/restaurant', function() { + describe('with valid body', function() { + after( done => { + if (this.tempRestaurant) { + Restaurant.deleteRestaurant(this.tempRestaurant.id) + .then( ()=> done()) + .catch( err => done(err)); + } + }); + + it('should return restaurant', done => { + request.post(`${url}/api/restaurant`) + .send(exampleRestaurant) + .end((err, res) => { + if (err) return done (err); + expect(res.status).to.equal(200); + expect(res.body.restaurantname).to.equal(exampleRestaurant.restaurantname); + expect(res.body.address).to.equal(exampleRestaurant.address); + this.tempRestaurant = res.body; + done(); + }); + }); + }); + }); + + describe('PUT: /api/restaurant', function() { + describe('with valid id and body', function() { + before( done => { + Restaurant.createRestaurant(exampleRestaurant) + .then( restaurant => { + this.tempRestaurant = restaurant; + done(); + }) + .catch( err => done(err)); + }); + + after( done => { + if (this.tempRestaurant) { + Restaurant.deleteRestaurant(this.tempRestaurant.id) + .then( ()=> done()) + .catch(done); + } + }); + + it('should return restaurant', done => { + let updateRestaurant = { restaurantname: 'new restaurant name', address: 'new address'}; + request.put(`${url}/api/restaurant?id=${this.tempRestaurant.id}`) + .send(updateRestaurant) + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.id).to.equal(this.tempRestaurant.id); + for (var prop in updateRestaurant) { + expect(res.body[prop]).to.equal(updateRestaurant[prop]); + } + done(); + }); + }); + }); + }); +});