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..2c9b222 --- /dev/null +++ b/.gitignore @@ -0,0 +1,113 @@ + +# Created by https://www.gitignore.io/api/osx,linux,windows,node + +### OSX ### +*.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 + + +### 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 diff --git a/README.md b/README.md new file mode 100644 index 0000000..ace6941 --- /dev/null +++ b/README.md @@ -0,0 +1,37 @@ +# Express REST API + +## Overview + +This is a basic Express API app that allows a developer to POST, GET and DELETE data from an API. A developer should be able to see the appropriate response statuses when interacting with the API. + +## How do I use this app? + +* Clone this repo and run the command `npm i` in your terminal to install all of the dependencies. + +* You will also need to run the command `brew install httpie`. For this app, the requests used in the terminal are formatted via HTTPie CLI. + +* Open 2 panes in your terminal to get started. You should see response status codes in both terminal panes. + +* Be sure that you are in the root of the repo directory before attempting to initiate the port to the server. To do this, run `node server.js` in the first terminal pane. + * `server running:` followed by your PORT number should be logged in the terminal + +### POST requests + * **i.e.** 200 OK request: `http POST localhost:3000/api/pin title="sample title" skill="sample skill"` + * You should receive a response with the content of the appropriate pin you just posted. + * **i.e.** 400 BAD request: `http POST localhost:3000/api/pin` (no title and skill is attached to POST request) + * You should receive a response with a 'Bad Request' message. + +### GET requests + * **i.e.** 200 OK request: `http localhost:3000/api/pin?id=17b389b0-c2ff-11e6-9794-69f9c8e1c4f5` + * You must pass in a query string equal to the unique id of the pin you want to retrieve. + * You should receive a response with the content of the appropriate pin. + * **i.e.** 400 BAD request: `http localhost:3000/api/pin` + * You should receive a response with a 'Bad Request' message. + +### DELETE requests + * **i.e.** 204 No Content request: `http DELETE localhost:3000/api/pin?id=69df11c0-c2fd-11e6-8512-d5d43d0553c1` + * You must pass in a query string equal to the unique id of the pin you want to delete. + * **i.e.** 400 BAD request: `http localhost:3000/api/pin` + * You should receive a response with a 'Bad Request' message. + +GET, POST and DELETE request commands should be run in the second terminal pane. JSON files should be posted and deleted from the `/data/pin` folder depending on your terminal commands. diff --git a/data/pin/22f30480-c35f-11e6-b975-93db3f47cc6c.json b/data/pin/22f30480-c35f-11e6-b975-93db3f47cc6c.json new file mode 100644 index 0000000..928f168 --- /dev/null +++ b/data/pin/22f30480-c35f-11e6-b975-93db3f47cc6c.json @@ -0,0 +1 @@ +{"id":"22f30480-c35f-11e6-b975-93db3f47cc6c","title":"test title","skill":"test skill"} \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js new file mode 100644 index 0000000..b16e376 --- /dev/null +++ b/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/lib/storage.js b/lib/storage.js new file mode 100644 index 0000000..025ae15 --- /dev/null +++ b/lib/storage.js @@ -0,0 +1,44 @@ +'use strict'; + +const Promise = require('bluebird'); +const fs = Promise.promisifyAll(require('fs'), {suffix: 'Prom'}); +const createError = require('http-errors'); +const debug = require('debug')('pin:storage'); + +module.exports = exports = {}; + +exports.createItem = function(schemaName, item) { + debug('createItem'); + + 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'); + + 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'); + + 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))); +}; diff --git a/model/pin.js b/model/pin.js new file mode 100644 index 0000000..7f0cbbb --- /dev/null +++ b/model/pin.js @@ -0,0 +1,38 @@ +'use strict'; + +const uuid = require('node-uuid'); +const createError = require('http-errors'); +const debug = require('debug')('pin:pin'); +const storage = require('../lib/storage.js'); + +const Pin = module.exports = function(title, skill) { + debug('pin constructor'); + + if (!title) throw createError(400, 'expected title'); + if (!skill) throw createError(400, 'expected skill'); + + this.id = uuid.v1(); + this.title = title; + this.skill = skill; +}; + +Pin.createPin = function(_pin) { + debug('createPin'); + + try { + let pin = new Pin(_pin.title, _pin.skill); + return storage.createItem('pin', pin); + } catch (err) { + return Promise.reject(err); + } +}; + +Pin.fetchPin = function(id) { + debug('fetchPin'); + return storage.fetchItem('pin', id); +}; + +Pin.deletePin = function(id) { + debug('deletePin'); + return storage.deleteItem('pin', id); +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..5feb968 --- /dev/null +++ b/package.json @@ -0,0 +1,41 @@ +{ + "name": "08-vanilla_rest_api", + "version": "1.0.0", + "description": "", + "main": "gulpfile.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "start": "DEBUG='note*' node server.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/kcirekcom/08-vanilla_rest_api.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/kcirekcom/08-vanilla_rest_api/issues" + }, + "homepage": "https://github.com/kcirekcom/08-vanilla_rest_api#readme", + "dependencies": { + "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", + "gulp": "^3.9.1", + "gulp-eslint": "^3.0.1", + "gulp-mocha": "^3.0.1", + "mocha": "^3.2.0", + "superagent": "^3.3.0" + } +} diff --git a/server.js b/server.js new file mode 100644 index 0000000..c627fad --- /dev/null +++ b/server.js @@ -0,0 +1,55 @@ +'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')('pin:server'); + +const app = express(); +const Pin = require('./model/pin.js'); +const PORT = 3000; + +app.use(morgan('dev')); + +app.post('/api/pin', jsonParser, function(req, res, next) { + debug('POST: /api/pin'); + + Pin.createPin(req.body) + .then(pin => res.json(pin)) + .catch(err => next(err)); +}); + +app.get('/api/pin', function(req, res, next) { + debug('GET: /api/pin'); + + Pin.fetchPin(req.query.id) + .then(pin => res.json(pin)) + .catch(err => next(err)); +}); + +app.delete('/api/pin', function(req, res, next) { + debug('DELETE: /api/pin'); + + Pin.deletePin(req.query.id) + .then(() => res.status(204).send()) + .catch(err => next(err)); +}); + +// eslint-disable-next-line +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 running: ${PORT}`); +}); diff --git a/test/pin-route-test.js b/test/pin-route-test.js new file mode 100644 index 0000000..b28e9e6 --- /dev/null +++ b/test/pin-route-test.js @@ -0,0 +1,70 @@ +'use strict'; + +const request = require('superagent'); +const expect = require('chai').expect; + +require('../server.js'); + +describe('Pin Routes', function() { + var pin = null; + describe('POST: /api/pin', function() { + it('should return a pin', function(done) { + request.post('localhost:3000/api/pin') + .send({title: 'test title', skill: 'test skill'}) + .end((err, res) => { + if(err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.title).to.equal('test title'); + expect(res.body.skill).to.equal('test skill'); + pin = res.body; + done(); + }); + }); + it('should return a 400 bad request error', function(done) { + request.post('localhost:3000/api/pin') + .end((res) => { + expect(res.status).to.equal(400); + done(); + }); + }); + }); + + describe('GET: /api/pin', function() { + it('should return a pin', function(done) { + request.get(`localhost:3000/api/pin?id=${pin.id}`) + .end((err, res) => { + if(err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.title).to.equal('test title'); + expect(res.body.skill).to.equal('test skill'); + done(); + }); + }); + it('should return a 404 pin not found error', function(done) { + request.get('localhost:3000/api/pin?id==513dh46ef') + .end((res) => { + expect(res.status).to.equal(404); + done(); + }); + }); + it('should return a 400 bad request error', function(done) { + request.get('localhost:3000/api/pin') + .end((res) => { + expect(res.status).to.equal(400); + done(); + }); + }); + }); + + describe('DELETE: /api/pin', function() { + it('should return no pin content', function(done) { + request.delete(`localhost:3000/api/pin?id=${pin.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(); + }); + }); + }); +});