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"
}
102 changes: 102 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@

# Created by https://www.gitignore.io/api/macos,node,vim,vim

### 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*
node_modules

# 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


### Vim ###
# swap
# session
# temporary
# auto-generated tag files

### project specific ###
temp
img/test.bmp
84 changes: 84 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Express Single Resource API with middleware

This express single resource API allows a user to make GET, PUT, and POST requests to the Artist object. The user can POST a new Artist name and genre, receive an id, and can get the Artist by that id.

### Set-Up

In your Terminal

```sh
$ git clone <repository url>
$ cd 12-express_middleware
$ npm i
```
This will install the proper dependencies. You should receive the following in your package.json file:

```sh
"dependencies": {
"bluebird": "^3.4.6",
"body-parser": "^1.15.2",
"chai": "^3.5.0",
"debug": "^2.4.5",
"express": "^4.14.0",
"http-errors": "^1.5.1",
"mocha": "^3.2.0",
"morgan": "^1.7.0",
"node-uuid": "^1.4.7",
"superagent": "^3.3.1"
}
```

Run `node server.js` or to start your server. Or run `npm run start` to include debug while starting your server. You will receive a response of 'server live on PORT: `<PORT>`'


### Use

Making a POST request
* Run `http POST localhost:<PORT>/api/artist name='<name>' genre='<genre>'`
* This will update the Artist object to show `name:` `genre:` and `id:`
* You will also receive a status code of 200.

Example:
```sh
HTTP/1.1 200 OK
Access-Control-Allow-Headers: *
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 79
Content-Type: application/json; charset=utf-8
Date: Wed, 21 Dec 2016 01:42:55 GMT
ETag: W/"4f-XrtcY5ELsfZ6vIlKoUtB+Q"
X-Powered-By: Express

{
"genre": "Punk",
"id": "cb000020-c71e-11e6-b55a-156f3ac3297a",
"name": "Blink-182"
}
```

Making a GET request
* Run `http localhost:<PORT>/api/artist?id=<id>`
* You must copy and paste the id from the post request.
* You will also receive a status code of 200.

Example:
```sh
HTTP/1.1 200 OK
Access-Control-Allow-Headers: *
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 40
Content-Type: application/json; charset=utf-8
Date: Wed, 21 Dec 2016 01:43:28 GMT
ETag: W/"28-ivjiv1YIQTFvK7z9Yn5eIA"
X-Powered-By: Express

[
"cb000020-c71e-11e6-b55a-156f3ac3297a"
]
```

* If you run `http localhost:<PORT>/api/artist` you should receive a 400 status code, and a message of 'bad request'

* If you run `http POST localhost:<PORT>/api/artist` you should receive a 400 status code, and a message of 'bad request'
1 change: 1 addition & 0 deletions data/artist/cb000020-c71e-11e6-b55a-156f3ac3297a.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"cb000020-c71e-11e6-b55a-156f3ac3297a","name":"Blink-182","genre":"Punk"}
1 change: 1 addition & 0 deletions data/artist/ceb2b430-c7a8-11e6-8966-5197e7604b92.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"ceb2b430-c7a8-11e6-8966-5197e7604b92","name":"U2","genre":"easy listening"}
23 changes: 23 additions & 0 deletions gulpfile.js
Original file line number Diff line number Diff line change
@@ -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', 'task']);
});

gulp.task('default', ['dev']);
7 changes: 7 additions & 0 deletions lib/cors-middleware.js
Original file line number Diff line number Diff line change
@@ -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();
};
21 changes: 21 additions & 0 deletions lib/err-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict';

const createError = require('http-errors');
const debug = require('debug')('artist:err-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();
};
54 changes: 54 additions & 0 deletions lib/storage.js
Original file line number Diff line number Diff line change
@@ -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')('music-artists: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 => {
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(name => name.split('.json')[0]))
.catch( err => Promise.reject(createError(404, err.message)));
};
61 changes: 61 additions & 0 deletions model/music-artists.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
'use strict';

const uuid = require('node-uuid');
const createError = require('http-errors');
const debug = require('debug')('music-artists:music-artists');
const storage = require('../lib/storage.js');

const Artist = module.exports = function(name, genre) {
debug('artist constructor');

if(!name) throw createError(400, 'expected name');
if(!genre) throw createError(400, 'expected genre');

this.id = uuid.v1();
this.name = name;
this.genre = genre;

};

Artist.createArtist = function(_artist) {
debug('createArtist');

try {
let artist = new Artist(_artist.name, _artist.genre);
return storage.createItem('artist', artist);
} catch (err) {
return Promise.reject(createError(400, err.message));
}
};

Artist.fetchArtist = function(id) {
debug('fetchArtist');

return storage.fetchItem('artist', id);
};

Artist.updateArtist = function(id, _artist) {
debug('updateArtist');

return storage.fetchItem('artist', id)
.catch( err => Promise.reject(createError(404, err.message)))
.then( artist => {
for (var prop in artist) {
if (prop === 'id') continue;
if (_artist[prop]) artist[prop] = _artist[prop];
}
return storage.createItem('artist', artist);
});
};

Artist.deleteArtist = function(id) {
debug('deleteArtist');

return storage.deleteItem('artist', id);
};

Artist.fetchIDs = function() {
debug('fetchIDs');

return storage.availIDs('artist');
};
Loading