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
110 changes: 110 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# Mongo Express Two Resource API

This two resource RESTful API uses Express.js to handle server routing, and Mongodb to serve as the database.

### Set-Up

In your Terminal

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

```sh
"dependencies": {
"bluebird": "^3.4.7",
"body-parser": "^1.15.2",
"cors": "^2.8.1",
"debug": "^2.6.0",
"express": "^4.14.0",
"mongoose": "^4.7.5",
"morgan": "^1.7.0"
"chai": "^3.5.0",
"mocha": "^3.2.0",
"superagent": "^3.3.1"
}
```

### Use

You will need to have 3 terminal shells open to use this application.

* In one shell, run `mongod` to start the database.
* In another shell, run `npm run start`. You will receive a response of 'server live on PORT: `<PORT>`'
* The last shell will be used to make GET, POST, PUT, and DELETE requests


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"
}
```
To access the additional resource, you can run `http POST localhost:<PORT>/api/library name='<name>'`
* This will update the Library object to show `name:` `genre:` and `id:`
* You will also receive a status code of 200.

Making a GET request
* Run `http localhost:<PORT>/api/artist<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"
]
```
To access the additional resource, you can run `http localhost:<PORT>/api/library/<libraryID>`
* This will update the Library object to show `name:` `genre:` and `id:`
* You will also receive a status code of 200.

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

Example:
```sh
HTTP/1.1 204 NO CONTENT
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
```
To access the additional resource, you can run `http DELETE localhost:<PORT>/api/library/<libraryID>`
* This will update the Library object to show <libraryID> deleted.
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']);
28 changes: 28 additions & 0 deletions lib/error-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict';

const createError = require('http-errors');
const debug = require('debug')('artist:error-middleware');

module.exports = function(err, req, res, next) {
debug('error middleware');

console.error('msg:', err.message);
console.error('name:', err.name);

if(err.status) {
res.status(err.status).send(err.name);
next();
return;
}

if(err.name === 'ValidationError') {
err = createError(400, err.message);
res.status(err.status).send(err.name);
next();
return;
}

err = createError(500, err. message);
res.status(err.status).send(err.name);
next();
};
12 changes: 12 additions & 0 deletions model/artist.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const artistSchema = Schema({
name: {type: String, required: true},
genre: {type: String, required: true},
libraryID: {type: Schema.Types.ObjectId, required: true}
});

module.exports = mongoose.model('artist', artistSchema);
55 changes: 55 additions & 0 deletions model/library.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
'use strict';

const mongoose = require('mongoose');
const createError = require('http-errors');
const debug = require('debug')('artist:library');
const Schema = mongoose.Schema;

const Artist = require('./artist.js');

const librarySchema = Schema({
name: { type: String, required: true},
timestamp: { type: Date, required: true},
artists: [{ type: Schema.Types.ObjectId, ref: 'artist'}]
});

const Library = module.exports = mongoose.model('library', librarySchema);

Library.findByIdAndAddArtist = function(id, artist) {
debug('findByIdAndAddArtist');
console.log(id);
return Library.findById(id)
.catch( err => Promise.reject(createError(404, err.message)))
.then( library => {
console.log(library);
artist.libraryID = library._id;
this.tempLibrary = library;
return new Artist(artist).save();
})
.then( artist => {
this.tempLibrary.artists.push(artist._id);
this.tempArtist = artist;
return this.tempLibrary.save();
})
.then( () => {
return this.tempArtist;
});
};

Library.findByIdAndRemoveArtist = function(id) {
debug('findByIdAndRemoveArtist');

return Library.findById(id)
.catch( err => Promise.reject(createError(404, err.message)))
.then( artist => {
this.tempArtist = artist;
return Artist.findByIdAndRemove(artist._id);
})
.then( () => Library.findById(this.tempArtist.libraryID))
.then( library => {
library.artists.splice(library.artists.indexOf(this.tempArtist._id), 1);
this.tempLibrary = library;
return this.tempLibrary;
});

};
38 changes: 38 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "14-mongo_express_two_resource_api",
"version": "1.0.0",
"description": "",
"main": "gulpfile.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "DEBUG='artist*' mocha",
"start": "DEBUG='artist*' node server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/dbecker4130/14-mongo_express_two_resource_api.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/dbecker4130/14-mongo_express_two_resource_api/issues"
},
"homepage": "https://github.com/dbecker4130/14-mongo_express_two_resource_api#readme",
"devDependencies": {
"bluebird": "^3.4.7",
"body-parser": "^1.15.2",
"cors": "^2.8.1",
"debug": "^2.6.0",
"express": "^4.14.0",
"mongoose": "^4.7.5",
"morgan": "^1.7.0"
},
"dependencies": {
"chai": "^3.5.0",
"mocha": "^3.2.0",
"superagent": "^3.3.1"
}
}
Loading