Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -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"
}
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
61 changes: 12 additions & 49 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,53 +1,16 @@
![cf](https://i.imgur.com/7v5ASc8.png) 11: Single Resource Express API
======
# Express API - Lab 11

## Submission Instructions
* fork this repository & create a new branch for your work
* write all of your code in a directory named `lab-` + `<your name>` **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:

## Learning Objectives
* students will be able to create a single resource API using the express framework
* students will be able to leverage 3rd party helper modules for debugging, logging, and handling errors
This app is an API that utilizes the express framework. Following REST architecture the this app allows a resource to be READ, CREATED and DELETED. It runs the appropriate tests for getting the correct data and error messages.

## Requirements
### How to use:

#### Configuration
* `package.json`
* `.eslintrc`
* `.gitignore`
* `README.md`
* your `README.md` should include detailed instructions on how to use your API

#### Feature Tasks
* create an HTTP server using `express`
* create a object constructor that creates a _simple resource_ with at least 3 properties
* it can **not** have the same properties as the in-class sample code (other than the `id`)
* a unique `id` property should be included *(node-uuid)*
* include two additional properties of your choice
* use the JSON parser included with the `body-parser` module as a middleware component to parse the request body on `POST` and `PUT` routes
* use the npm `debug` module to log the methods in your application
* create an `npm` script to automate the `debug` process and start the server
* persist your API data using the storage module and file system persistence

#### Server Endpoints
* **`/api/simple-resource-name`**
* `POST` request
* pass data as stringifed JSON in the body of a **POST** request to create a new resource
* `GET` request
* pass `?id=<uuid>` as a query string parameter to retrieve a specific resource (as JSON)
* `DELETE` request
* pass `?id=<uuid>` in the query string to **DELETE** a specific resource
* this should return a 204 status code with no content in the body

#### Tests
* write a test to ensure that your api returns a status code of 404 for routes that have not been registered
* write tests to ensure the `/api/simple-resource-name` endpoint responds as described for each condition below:
* `GET`: test 404, it should respond with 'not found' for valid requests made with an id that was not found
* `GET`: test 400, it should respond with 'bad request' if no id was provided in the request
* `GET`: test 200, it should contain a response body for a request made with a valid id
* `POST`: test 400, it should respond with 'bad request' if no request body was provided or the body was invalid
* `POST`: test 200, it should respond with the body content for a post request with a valid body
* Run the server from the command line using `npm run start`
* Open a separate tab in the terminal
* From the second tab start by entering `http [optional request method] :8000/api/song [properties/id]`
* `GET` requests do not require a request method in the command line
* followed by the songs items id like `id=='[unique-song-id]'`
* `POST` requests are made with `POST` as the request method
* followed by key-value pairs like `name=[item-name]`
* `DELETE` requests are made like `GET` only with the `DELETE` as the request method
57 changes: 57 additions & 0 deletions lib/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
'use strict';

const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'), { suffix: 'Prom' });
const createError = require('http-errors');
const debug = require('debug')('song: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(err));
};

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) {
Promise.reject(err);
}
})
.catch( err => Promise.reject(err));
};

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 item'));

return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`)
.then( () => {
try {
debug('song has been deleted');
return;
} catch (err) {
Promise.reject(err);
}
})
.catch( err => Promise.reject(err));
};
40 changes: 40 additions & 0 deletions model/song.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
'use strict';

const uuidv4 = require('uuid/v4');
const createError = require('http-errors');
const debug = require('debug')('storage:song');
const storage = require('../lib/storage.js');

const Song = module.exports = function(name, band, year) {
debug('song contructor');

if (!name) return Promise.reject(createError(400, 'expected name'));
if (!band) return Promise.reject(createError(400, 'expected band'));
if (!year) return Promise.reject(createError(400, 'expected year'));

this.id = uuidv4();
this.name = name;
this.band = band;
this.year = year;
};

Song.createSong = function(_song) {
debug('createSong');

try {
let song = new Song(_song.name, _song.band, _song.year);
return storage.createItem('song', song);
} catch (err) {
return Promise.reject(err);
}
};

Song.fetchSong = function(id) {
debug('fetchSong');
return storage.fetchItem('song', id);
};

Song.deleteSong = function(id) {
debug('deleteSong');
return storage.deleteItem('song', id);
};
35 changes: 35 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "11-express-api",
"version": "1.0.0",
"description": "![cf](https://i.imgur.com/7v5ASc8.png) 11: Single Resource Express API ======",
"main": "server.js",
"scripts": {
"test": "mocha",
"start": "DEBUG='note*' node server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/nickjaz/11-express-api.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/nickjaz/11-express-api/issues"
},
"homepage": "https://github.com/nickjaz/11-express-api#readme",
"dependencies": {
"bluebird": "^3.5.0",
"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.4.2",
"superagent": "^3.5.2"
}
}
54 changes: 54 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
'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')('song:server');
const Song = require('./model/song.js');

const PORT = process.env.PORT || 3000;
const app = express();

app.use(morgan('dev'));

app.get('/api/song', function(req, res, next) {
debug('GET: /api/song');

Song.fetchSong(req.query.id)
.then( song => res.json(song))
.catch( err => next(err));
});

app.post('/api/song', jsonParser, function(req, res, next) {
debug('POST: /api/song');

Song.createSong(req.body)
.then( song => res.json(song) )
.catch( err => next(err) );
});

app.delete('/api/song', function(req, res, next) {
debug('DELETE: /api/song');

Song.deleteSong(req.query.id)
.then( () => createError(204, 'song deleted') )
.catch( err => next(err) );
});

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, () => {
debug('server up:', PORT);
});
65 changes: 65 additions & 0 deletions test/song-route-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
'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('POST: should return 400', function(done) {
request.post('localhost:8000/api/song')
.send({album: 'jazzhands', trippy: 'false'})
.end((err, res) => {
expect(res.status).to.equal(400);
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('GET: should return 404', function(done) {
request.get('localhost:8000/api/album?id=12345')
.end(function(err, res) {
expect(res.status).to.equal(404);
done();
});
});

it('GET: should return 400', function(done) {
request.get('localhost:8000/api/song?=12344')
.end(function(err, res) {
expect(res.status).to.equal(400);
done();
});
});
});
});