diff --git a/lab-nathan/.eslintignore b/lab-nathan/.eslintignore new file mode 100644 index 0000000..c6abca4 --- /dev/null +++ b/lab-nathan/.eslintignore @@ -0,0 +1,6 @@ +**/node_modules/* +**/vendor/* +**/*.min.js +**/coverage/* +**/build/* +**/assets/* diff --git a/lab-nathan/.eslintrc b/lab-nathan/.eslintrc new file mode 100644 index 0000000..c8dfef7 --- /dev/null +++ b/lab-nathan/.eslintrc @@ -0,0 +1,23 @@ +{ + "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 + }, + "parserOptions": { + "ecmaFeatures": { + "modules": true, + "experimentalObjectRestSpread": true, + "impliedStrict": true + } + }, + "extends": "eslint:recommended" +} diff --git a/lab-nathan/.gitignore b/lab-nathan/.gitignore new file mode 100644 index 0000000..115b88e --- /dev/null +++ b/lab-nathan/.gitignore @@ -0,0 +1,138 @@ +# Created by https://www.gitignore.io/api/osx,vim,node,macos,windows + +### 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 + +### Node ### +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.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 + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Typescript v1 declaration files +typings/ + +# 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 + +# dotenv environment variables file +.env + + +### OSX ### + +# Icon must end with two \r + +# Thumbnails + +# Files that might appear in the root of a volume + +# Directories potentially created on remote AFP share + +### Vim ### +# swap +[._]*.s[a-v][a-z] +[._]*.sw[a-p] +[._]s[a-v][a-z] +[._]sw[a-p] +# session +Session.vim +# temporary +.netrwhist +*~ +# auto-generated tag files +tags + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# End of https://www.gitignore.io/api/osx,vim,node,macos,windows + +data diff --git a/lab-nathan/README.md b/lab-nathan/README.md new file mode 100644 index 0000000..b3f86ca --- /dev/null +++ b/lab-nathan/README.md @@ -0,0 +1,17 @@ +# Nathan's Book API using Express + +This HTTP REST API uses express to handle to manage routing and middleware. It features endpoints for a book resource. + +## Book Properties +**title**: string \ +**author**: string \ +**date**: number \ +**genre**: string + + +## Endpoints + +### GET `/` +### GET `/api/book?id=` +### POST `/api/book?id=` +### DELETE `/api/book?id=` \ No newline at end of file diff --git a/lab-nathan/lib/fs-promises.js b/lab-nathan/lib/fs-promises.js new file mode 100644 index 0000000..43609f5 --- /dev/null +++ b/lab-nathan/lib/fs-promises.js @@ -0,0 +1,70 @@ +'use strict'; + +const fs = require('fs'); +const debug = require('debug')('book:fs-promises'); + +let fsPromises = {}; + +module.exports = fsPromises; + +fsPromises.createDirectory = function(path) { + debug('createDirectory'); + return new Promise(function(resolve, reject) { + fs.mkdir(path, function(error) { + if (error && error.code !== 'EEXIST') { + reject(error); + } else { + resolve(); + } + }); + }); +}; + +fsPromises.writeFile = function(path, item) { + debug('writeFile'); + return new Promise(function(resolve, reject) { + fs.writeFile(path, item, function(error) { + if (error) { + reject(error); + } else { + resolve(); + } + }); + }); +}; + +fsPromises.readFile = function(path) { + debug('readFile'); + return new Promise((resolve, reject) => { + fs.readFile(path, function(error, buffer) { + if (error) { + reject(error); + } else { + resolve(JSON.parse(buffer.toString())); + } + }); + }); +}; + +fsPromises.deleteFile = function(path) { + debug('deleteFile'); + return new Promise((resolve, reject) => { + fs.unlink(path, function(error) { + if (error) { + reject(error); + } else { + resolve(); + } + }); + }); +}; + +fsPromises.exists = function(path) { + debug('exists'); + return new Promise(function(resolve) { + fs.exists(path, function(exists) { + resolve(exists); + }); + }); +}; + diff --git a/lab-nathan/lib/storage.js b/lab-nathan/lib/storage.js new file mode 100644 index 0000000..8b7da9f --- /dev/null +++ b/lab-nathan/lib/storage.js @@ -0,0 +1,33 @@ +'use strict'; + +const debug = require('debug')('book:storage'); +const fsPromises = require('./fs-promises.js'); + +let storage = {}; + +module.exports = storage; + +storage.createItem = function(categoryName, item) { + debug('createItem'); + return fsPromises.createDirectory(`${__dirname}/../data/`) + .then(fsPromises.createDirectory(`${__dirname}/../data/${categoryName}`)) + .then(fsPromises.writeFile(`${__dirname}/../data/${categoryName}/${item.id}.json`, JSON.stringify(item))) + .then(() => item) + .catch(error => Promise.reject(error)); +}; + +storage.getItem = function(categoryName, id) { + debug('getItem'); + return fsPromises.readFile(`${__dirname}/../data/${categoryName}/${id}.json`) + .catch(error => Promise.reject(error)); +}; + +storage.removeItem = function(categoryName, id) { + debug('removeItem'); + return fsPromises.deleteFile(`${__dirname}/../data/${categoryName}/${id}.json`) + .catch(error => Promise.reject(error)); +}; + +storage.itemExists = function(categoryName, id) { + return fsPromises.exists(`${__dirname}/../data/${categoryName}/${id}.json`); +}; \ No newline at end of file diff --git a/lab-nathan/model/book.js b/lab-nathan/model/book.js new file mode 100644 index 0000000..7c85d4c --- /dev/null +++ b/lab-nathan/model/book.js @@ -0,0 +1,70 @@ +'use strict'; + +const uuidv4 = require('uuid/v4'); +const debug = require('debug')('book:book'); +const storage = require('../lib/storage.js'); +const createError = require('http-errors'); + +module.exports = Book; + +function Book(title, author, date, genre) { + debug('Book'); + + if (!title) { + throw new Error('Title not provided.'); + } + + if (!author) { + throw new Error('Author not provided.'); + } + + if (!date) { + throw new Error('Date not provided.'); + } + + if (!genre) { + throw new Error('Genre not provided.'); + } + + this.id = uuidv4(); + this.title = title; + this.author = author; + this.date = date; + this.genre = genre; +} + +Book.get = function(id) { + debug('get'); + + if (!id) { + return Promise.reject(createError(400, 'Id not provided.')); + } + + return storage.itemExists('book', id) + .then(function(exists) { + if (exists) { + return Promise.resolve(); + } + else { + return Promise.reject(createError(404, 'Book not found.')); + } + }) + .then(() => Promise.resolve(storage.getItem('book', id))); +}; + +Book.create = function(bookData) { + debug('create'); + + try { + let book = new Book(bookData.title, bookData.author, bookData.date, bookData.genre); + return storage.createItem('book', book); + } catch (error) { + return Promise.reject(error); + } +}; + +Book.delete = function(id) { + debug('delete'); + + return storage.removeItem('book', id); +}; \ No newline at end of file diff --git a/lab-nathan/package.json b/lab-nathan/package.json new file mode 100644 index 0000000..be7b956 --- /dev/null +++ b/lab-nathan/package.json @@ -0,0 +1,34 @@ +{ + "name": "11-express-api", + "version": "1.0.0", + "description": "![cf](https://i.imgur.com/7v5ASc8.png) 11: Single Resource Express API\r ======", + "main": "server.js", + "scripts": { + "test": "mocha", + "start": "DEBUG='note*' node server.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nharren/11-express-api.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/nharren/11-express-api/issues" + }, + "homepage": "https://github.com/nharren/11-express-api#readme", + "dependencies": { + "body-parser": "^1.17.2", + "debug": "^2.6.8", + "express": "^4.15.3", + "http-errors": "^1.6.1", + "morgan": "^1.8.2", + "uuid": "^3.1.0" + }, + "devDependencies": { + "chai": "^4.1.0", + "mocha": "^3.5.0", + "superagent": "^3.5.2" + } +} diff --git a/lab-nathan/server.js b/lab-nathan/server.js new file mode 100644 index 0000000..56fb113 --- /dev/null +++ b/lab-nathan/server.js @@ -0,0 +1,65 @@ +'use strict'; + +const morgan = require('morgan'); +const debug = require('debug')('book:server'); +const jsonParser = require('body-parser').json(); +const express = require('express'); +const createError = require('http-errors'); +const Book = require('./model/Book.js'); +const app = express(); + +app.use(morgan('dev')); + +app.get('/', function(request, response) { + debug('GET: /'); + response.send('Welcome to Nathan\'s Book API using Express.'); +}); + +app.get('/api/book', function(request, response, next) { + debug('GET: /api/book'); + Book.get(request.query.id) + .then(book => response.json(book)) + .catch(error => next(error)); +}); + +app.post('/api/book', jsonParser, function(request, response, next) { + debug('POST: /api/book'); + + if (Object.keys(request.body).length === 0) { + return next(createError(400, 'Book not provided.')); + } + + Book.create(request.body) + .then(book => response.json(book)) + .catch(error => next(createError(400, error.message))); +}); + +app.delete('/api/book', function(request, response, next) { + debug('DELETE: /api/book'); + Book.delete(request.query.id) + .then(() => response.sendStatus(204)) + .catch(error => next(error)); +}); + +app.use(function(error, request, response, next) { + debug('error middleware'); + console.error(error); + + if (!next) { + error = createError(404); + } + + if (error.status) { + return response.status(error.status).send(error.message); + } + + error = createError(500, error.message); + debug(error); + response.status(error.status).send(error.name); +}); + +const PORT = process.env.PORT || 3000; + +app.listen(PORT, function() { + debug(`Server started on port ${PORT}.`); +}); \ No newline at end of file diff --git a/lab-nathan/test/server-test.js b/lab-nathan/test/server-test.js new file mode 100644 index 0000000..eccbd35 --- /dev/null +++ b/lab-nathan/test/server-test.js @@ -0,0 +1,153 @@ +'use strict'; + +const expect = require('chai').expect; +const request = require('superagent'); + +// require('../server.js'); + +let id; + +describe('Book API', function() { + it ('should return \'bad request\' if route not found.', function(done) { + request.get('localhost:8000/ponies', function(error, response) { + expect(response.status).to.equal(404); + done(); + }); + }); + + describe('GET: /', function() { + it ('should return a welcome message.', function(done) { + request.get('localhost:8000/', function(error, response) { + expect(response.text).to.equal('Welcome to Nathan\'s Book API using Express.'); + done(); + }); + }); + }); + + describe('POST: /api/book/', function() { + it ('should return a book.', function(done) { + request.post('localhost:8000/api/book') + .send({ + title: 'Hamlet', + author: 'Shakespeare', + date: 1599, + genre: 'Drama' + }) + .end(function(error, response) { + id = response.body.id; + expect(response.status).to.equal(200); + expect(response.body.id).to.be.a('string'); + expect(response.body.title).to.equal('Hamlet'); + expect(response.body.author).to.equal('Shakespeare'); + expect(response.body.date).to.equal(1599); + expect(response.body.genre).to.equal('Drama'); + done(); + }); + }); + + it ('should return an error if posting with no body.', function(done) { + request.post('localhost:8000/api/book') + .send() + .end(function(error, response) { + expect(response.status).to.equal(400); + expect(response.text).to.equal('Book not provided.'); + done(); + }); + }); + + it ('should return an error if posting with no title.', function(done) { + request.post('localhost:8000/api/book') + .send({ + author: 'Shakespeare', + date: 1599, + genre: 'Drama' + }) + .end(function(error, response) { + expect(response.status).to.equal(400); + expect(response.text).to.equal('Title not provided.'); + done(); + }); + }); + + it ('should return an error if posting with no author.', function(done) { + request.post('localhost:8000/api/book') + .send({ + title: 'Hamlet', + date: 1599, + genre: 'Drama' + }) + .end(function(error, response) { + expect(response.status).to.equal(400); + expect(response.text).to.equal('Author not provided.'); + done(); + }); + }); + + it ('should return an error if posting with no date.', function(done) { + request.post('localhost:8000/api/book') + .send({ + title: 'Hamlet', + author: 'Shakespeare', + genre: 'Drama' + }) + .end(function(error, response) { + expect(response.status).to.equal(400); + expect(response.text).to.equal('Date not provided.'); + done(); + }); + }); + + it ('should return an error if posting with no genre.', function(done) { + request.post('localhost:8000/api/book') + .send({ + title: 'Hamlet', + author: 'Shakespeare', + date: 1599, + }) + .end(function(error, response) { + expect(response.status).to.equal(400); + expect(response.text).to.equal('Genre not provided.'); + done(); + }); + }); + }); + + describe('GET: /api/book', function() { + it ('should return an error if id not provided.', function(done) { + request.get('localhost:8000/api/book', function(error, response) { + expect(response.status).to.equal(400); + expect(response.text).to.equal('Id not provided.'); + done(); + }); + }); + + it ('should return an error if id not found.', function(done) { + request.get('localhost:8000/api/book?id=1', function(error, response) { + expect(response.status).to.equal(404); + expect(response.text).to.equal('Book not found.'); + done(); + }); + }); + + it ('should return a book.', function(done) { + request.get(`localhost:8000/api/book?id=${id}`, function(error, response) { + expect(response.status).to.equal(200); + expect(response.body.id).to.be.a('string'); + expect(response.body.title).to.equal('Hamlet'); + expect(response.body.author).to.equal('Shakespeare'); + expect(response.body.date).to.equal(1599); + expect(response.body.genre).to.equal('Drama'); + done(); + }); + }); + }); + + describe('DELETE: /api/book', function() { + it ('should delete a book.', function(done) { + request.delete(`localhost:8000/api/book?id=${id}`, function(error, response) { + expect(response.status).to.equal(204); + done(); + }); + }); + }); +});