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..3c3629e --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/README.md b/README.md index 0aaf9f2..00e27b8 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,7 @@ -![cf](https://i.imgur.com/7v5ASc8.png) Lab 09: Vanilla REST API w/ Persistence -====== +# Vanilla API Persistence - 09 Lab -## Submission Instructions - * fork this repository & create a new branch for your work - * write all of your code in a directory named `lab-` + `` **e.g.** `lab-susan` - * push to your repository - * submit a pull request to this repository - * submit a link to your PR in canvas - * write a question and observation on canvas +### Description: +This app builds out an API where data is stored in the file system. This API stores song data with the schema of name, band, and year. -## Learning Objectives -* students will learn how to save resource data to the file system for a layer of data persistence -* students will learn how to refactor commonly used coding constructs into custom helper modules - -## Requirements - -#### Configuration -* `package.json` -* `.eslintrc` -* `.gitignore` -* `README.md` - * your `README.md` should include detailed instructions on how to use your API - * this should include documentation on how to access your API endpoints - -#### Feature Tasks -* continue working on your vanilla REST API -* refactor your routes to be contained in a separate module (ex: `route/resource-route.js`) -* refactor your `res` messages & status codes to be contained in a separate module (ex: `response.js`) -* refactor the `storage.js` module to use file system persistence - * use the `fs` module to create and read the associated data files - * the name of the file should contain the related resource id +### API: +The URL endpoint to access the api is `/api/song`. Using REST architecture the data is read, written and deleted using `GET`, `POST` and `DELETE` requests. diff --git a/data/song/943488f2-4bb6-4fa0-b0b9-fe8cec6b1943.json b/data/song/943488f2-4bb6-4fa0-b0b9-fe8cec6b1943.json new file mode 100644 index 0000000..fc9c198 --- /dev/null +++ b/data/song/943488f2-4bb6-4fa0-b0b9-fe8cec6b1943.json @@ -0,0 +1 @@ +{"id":"943488f2-4bb6-4fa0-b0b9-fe8cec6b1943","name":"test name","band":"test band","year":"test year"} \ No newline at end of file diff --git a/lib/parse-json.js b/lib/parse-json.js new file mode 100644 index 0000000..ae20196 --- /dev/null +++ b/lib/parse-json.js @@ -0,0 +1,30 @@ +'use strict'; + +module.exports = function(req) { + return new Promise((resolve, reject) => { + if(req.method === 'POST'|| req.method === 'PUT') { + var body = ''; + + req.on('data', data => { + body += data.toString(); + }); + + req.on('end', () => { + try { + req.body = JSON.parse(body); + resolve(req); + } catch (err) { + console.error(err); + reject(err); + } + }); + + req.on('error', err => { + console.error(err); + reject(err); + }); + return; + } + resolve(); + }); +}; diff --git a/lib/parse-url.js b/lib/parse-url.js new file mode 100644 index 0000000..6efe08e --- /dev/null +++ b/lib/parse-url.js @@ -0,0 +1,11 @@ +'use strict'; + +const parseQuery = require('querystring').parse; +const parseUrl = require('url').parse; + +module.exports = function(req) { + req.url = parseUrl(req.url); + req.url.query = parseQuery(req.url.query); + + return Promise.resolve(req); +}; diff --git a/lib/response.js b/lib/response.js new file mode 100644 index 0000000..b000606 --- /dev/null +++ b/lib/response.js @@ -0,0 +1,21 @@ +'use strict'; + +module.exports = exports = {}; + +exports.sendJSON = function(res, status, data) { + res.writeHead(status, { + 'Content-type': 'application/json' + }); + + res.write(JSON.stringify(data)); + res.end(); +}; + +exports.sendText = function(res, status, msg) { + res.writeHead(status, { + 'Content-type': 'text/plain' + }); + + res.write(msg); + res.end(); +}; diff --git a/lib/router.js b/lib/router.js new file mode 100644 index 0000000..bdd9d08 --- /dev/null +++ b/lib/router.js @@ -0,0 +1,61 @@ +'use strict'; + +const parseUrl = require('./parse-url.js'); +const parseJSON = require('./parse-json.js'); + +const Router = module.exports = function() { + this.routes = { + GET: {}, + POST: {}, + PUT: {}, + DELETE: {} + }; +}; + +Router.prototype.get = function(endpoint, callback) { + this.routes.GET[endpoint] = callback; +}; + +Router.prototype.post = function(endpoint, callback) { + this.routes.POST[endpoint] = callback; +}; + +Router.prototype.put = function(endpoint, callback) { + this.routes.PUT[endpoint] = callback; +}; + +Router.prototype.delete = function(endpoint, callback) { + this.routes.DELETE[endpoint] = callback; +}; + +Router.prototype.route = function() { + return (req, res) => { + Promise.all([ + parseUrl(req), + parseJSON(req) + ]) + .then( () => { + if(typeof this.routes[req.method][req.url.pathname] === 'function') { + this.routes[req.method][req.url.pathname](req, res); + return; + } + console.error('route not found'); + + res.writeHead(404, { + 'Content-type': 'text/plain' + }); + res.write('route not found'); + res.end(); + }) + .catch(err => { + console.log(err); + + res.writeHead(400, { + 'Content-type': 'text/plain' + }); + + res.write('bad result'); + res.end(); + }); + }; +}; diff --git a/lib/storage.js b/lib/storage.js new file mode 100644 index 0000000..52508a2 --- /dev/null +++ b/lib/storage.js @@ -0,0 +1,48 @@ +'use strict'; + +const Promise = require('bluebird'); +const fs = Promise.promisifyAll(require('fs'), { suffix: 'Prom' }); + +module.exports = exports = {}; + +exports.createItem = function(schemaName, item) { + if(!schemaName) return Promise.reject(new Error('expected schema name')); + if(!item) return Promise.reject(new Error('expected item')); + + let json = JSON.stringify(item); + + return fs.writeFileProm(`${__dirname}/../data/${schemaName}/${item.id}.json`, json) + .then( () => item) + .catch( err => Promise.reject(err)); +}; + +exports.fetchItem = function(schemaName, id) { + if(!schemaName) return Promise.reject(new Error('expected schema name')); + if(!id) return Promise.reject(new Error('expected id')); + + return fs.readFileProm(`${__dirname}/../data/${schemaName}/${id}.json`) + .then( data => { + try { + let item = JSON.parse(data.toString()); + return item; + } catch (err) { + Promise.reject(err); + } + }) + .catch( err => Promise.reject(err)); +}; + +exports.deleteItem = function(schemaName, item) { + if(!schemaName) return Promise.reject(new Error('expected schema name')); + if(!item) return Promise.reject(new Error('expected item')); + + return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${item.id}.json`) + .then( () => { + try { + console.log('song has been deleted'); + } catch (err) { + Promise.reject(err); + } + }) + .catch( err => Promise.reject(err)); +}; diff --git a/model/song.js b/model/song.js new file mode 100644 index 0000000..bd2bc72 --- /dev/null +++ b/model/song.js @@ -0,0 +1,14 @@ +'use strict'; + +const uuidv4 = require('uuid/v4'); + +module.exports = function(name, band, year) { + if (!name) throw new Error('expected name'); + if (!band) throw new Error('expected band'); + if (!year) throw new Error('expected year'); + + this.id = uuidv4(); + this.name = name; + this.band = band; + this.year = year; +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..d20f8b2 --- /dev/null +++ b/package.json @@ -0,0 +1,33 @@ +{ + "name": "09-vanilla_api_persistence", + "version": "1.0.0", + "description": "", + "main": "server.js", + "directories": { + "test": "test" + }, + "dependencies": { + "bluebird": "^3.5.0", + "uuid": "^3.1.0" + }, + "devDependencies": { + "chai": "^4.1.0", + "mocha": "^3.4.2", + "superagent": "^3.5.2" + }, + "scripts": { + "test": "mocha", + "start": "node server.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nickjaz/09-vanilla_api_persistence.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/nickjaz/09-vanilla_api_persistence/issues" + }, + "homepage": "https://github.com/nickjaz/09-vanilla_api_persistence#readme" +} diff --git a/route/song-route.js b/route/song-route.js new file mode 100644 index 0000000..cdef25d --- /dev/null +++ b/route/song-route.js @@ -0,0 +1,48 @@ +'use strict'; + +const storage = require('../lib/storage.js'); +const response = require('../lib/response.js'); +const Song = require('../model/song.js'); + +module.exports = function(router) { + router.get('/api/song', function(req, res) { + if(req.url.query.id) { + storage.fetchItem('song', req.url.query.id) + .then( song => { + response.sendJSON(res, 200, song); + }) + .catch( err => { + console.error(err); + response.sendText(res, 404, 'song not found'); + }); + return; + } + response.sendText(res, 400, 'bad request'); + }); + + router.post('/api/song', function(req, res) { + try { + var song = new Song(req.body.name, req.body.band, req.body.year); + storage.createItem('song', song); + response.sendJSON(res, 200, song); + } catch (err) { + console.error(err); + response.sendText(res, 400, 'bad request'); + } + }); + + router.delete('/api/song', function(req, res) { + if(req.url.query.id) { + storage.deleteItem('song', req.url.query.id) + .then( () => { + response.sendText(res, 204, 'song deleted'); + }) + .catch( err => { + console.log(err); + response.sendText(res, 404, 'song not found'); + }); + return; + } + response.sendText(res, 400, 'bad request'); + }); +}; diff --git a/server.js b/server.js new file mode 100644 index 0000000..6a61d84 --- /dev/null +++ b/server.js @@ -0,0 +1,14 @@ +'use strict'; + +const http = require('http'); +const Router = require('./lib/router.js'); +const PORT = process.env.PORT || 3000; +const router = new Router(); + +require('./route/song-route.js')(router); + +const server = http.createServer(router.route()); + +server.listen(PORT, function() { + console.log('listening on:', PORT); +}); diff --git a/test/song-route-test.js b/test/song-route-test.js new file mode 100644 index 0000000..b404848 --- /dev/null +++ b/test/song-route-test.js @@ -0,0 +1,68 @@ +'use strict'; + +const request = require('superagent'); +const expect = require('chai').expect; + +require('../server.js'); + +describe('Song Routes', function() { + var song = null; + + describe('POST: /api/song', function() { + it('should return a song', function(done) { + request.post('localhost:8000/api/song') + .send({name: 'test name', band: 'test band', year: 'test year'}) + .end((err, res) => { + if(err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal('test name'); + expect(res.body.band).to.equal('test band'); + expect(res.body.year).to.equal('test year'); + song = res.body; + done(); + }); + }); + + it('should return bad request', function(done) { + request.post('localhost:8000/api/song') + .send({album: 'test album', money: 'easy money'}) + .end((err, res) => { + expect(res.status).to.equal(400); + expect(res.text).to.equal('bad request'); + done(); + }); + }); + }); + + describe('GET: api/song', function() { + it('should return a song', function(done) { + request.get(`localhost:8000/api/song?id=${song.id}`) + .end(function(err, res){ + if(err) return done(err); + expect(res.status).to.equal(200); + expect(res.body.name).to.equal('test name'); + expect(res.body.band).to.equal('test band'); + expect(res.body.year).to.equal('test year'); + done(); + }); + }); + + it('should return song not found', function(done) { + request.get('localhost:8000/api/song?id=12345') + .end(function(err, res){ + expect(res.status).to.equal(404); + expect(res.text).to.equal('song not found'); + done(); + }); + }); + + it('should return bad request', function(done) { + request.get('localhost:8000/api/song?=12345') + .end(function(err, res){ + expect(res.status).to.equal(400); + expect(res.text).to.equal('bad request'); + done(); + }); + }); + }); +});