Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nikko Lab 14 #10

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
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
22 changes: 22 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"rules": {
"no-console": "off",
"indent": [ "error", 2 ],
"quotes": [ "error", "single" ],
"semi": ["error", "always"],
"linebreak-style": [ "error", "unix" ],
"no-unused-vars": [2, {"vars": "local", "args": "after-used"}]
},
"env": {
"es6": true,
"node": true,
"mocha": true,
"jasmine": true
},
"ecmaFeatures": {
"modules": true,
"experimentalObjectRestSpread": true,
"impliedStrict": true
},
"extends": "eslint:recommended"
}
120 changes: 120 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@

# Created by https://www.gitignore.io/api/node,osx,windows

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

#Test-Data
/data

#Node
/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

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

### 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/node,osx,windows
21 changes: 21 additions & 0 deletions gulpfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'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: 'nyan' }));
});

gulp.task('lint', function() {
return gulp.src(['**/*.js', '!node_modules'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});

gulp.task('dev', ['test', 'lint']);

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')('quiver:error-middleware');

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

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

if(err.status) {
res.status(err.status).send(err.message);
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();
};
14 changes: 14 additions & 0 deletions model/guitar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';

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

const guitarSchema = Schema({
name: { type: String, required: true},
type: { type: String, required: true},
make: { type: String, required: true},
timestamp: { type: Date, required: true},
quiverID: [{ type: Schema.Types.ObjectId, req: true}]
});

module.exports = mongoose.model('guitar', guitarSchema);
37 changes: 37 additions & 0 deletions model/quiver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

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

const Guitar = require('./guitar.js');

const quiverSchema = Schema({
owner: { type: String, required: true},
timestamp: { type: Date, required: true},
guitars: [{ type: Schema.Types.ObjectId, ref: 'guitar'}]
});

const Quiver = module.exports = mongoose.model('quiver', quiverSchema);

Quiver.findByIdAndAddGuitar = function(id, _guitar) {
debug('findByIdAndAddGuitar');

return Quiver.findById(id)
.catch( err => createError(404, err.message))
.then( quiver => {
_guitar.quiverID = quiver._id;
_guitar.timestamp = new Date();
this.tempQuiver = quiver;
return new Guitar(_guitar).save();
})
.then( guitar => {
this.tempGuitar = guitar;
this.tempQuiver.guitars.push(guitar._id);
return this.tempQuiver.save();
})
.then( () => {
return this.tempGuitar;
});
};
40 changes: 40 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"name": "14-mongo_express_two_resource_api",
"version": "1.0.0",
"description": "![CF](https://camo.githubusercontent.com/70edab54bba80edb7493cad3135e9606781cbb6b/687474703a2f2f692e696d6775722e636f6d2f377635415363382e706e67) Lab 14 - Mongo & Express Two Resource API ===",
"main": "gulpfile.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "DEBUG='quiver*' mocha",
"start": "DEBUG='quiver*' node server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/npisciotti1/14-mongo_express_two_resource_api.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/npisciotti1/14-mongo_express_two_resource_api/issues"
},
"homepage": "https://github.com/npisciotti1/14-mongo_express_two_resource_api#readme",
"dependencies": {
"bluebird": "^3.4.7",
"body-parser": "^1.17.0",
"cors": "^2.8.1",
"debug": "^2.6.1",
"express": "^4.15.0",
"http-errors": "^1.6.1",
"mongoose": "^4.8.5",
"morgan": "^1.8.1"
},
"devDependencies": {
"chai": "^3.5.0",
"expect": "^1.20.2",
"mocha": "^3.2.0",
"superagent": "^3.5.0"
}
}
56 changes: 56 additions & 0 deletions route/guitar-router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
'use strict';

const Router = require('express').Router;
const debug = require('debug')('quiver:guitar-router');
const createError = require('http-errors');
const jsonParser = require('body-parser').json();

const Quiver = require('../model/quiver.js');
const Guitar = require('../model/guitar.js');

const guitarRouter = module.exports = new Router();

guitarRouter.post('/api/quiver/:quiverID/guitar', jsonParser, function(req, res, next) {
debug('POST: /api/quiver/:quiverID/guitar');

req.body.timestamp = new Date();
Quiver.findByIdAndAddGuitar(req.params.quiverID, req.body)
.then( guitar => res.json(guitar))
.catch( () => next(createError(400, 'bad request')));
});

guitarRouter.get('/api/quiver/:quiverID/guitar/:guitarID', function(req, res, next) {
debug('GET: /api/quiver/:quiverID/guitar/:guitarID');

try {
Guitar.findById(req.params.guitarID)
.then( guitar => res.json(guitar))
.catch( () => next(createError(404, 'not found')));
} catch (err) {
next(createError(400, 'bad request'));
}
});

guitarRouter.put('/api/quiver/:quiverID/guitar/:guitarID', jsonParser, function(req, res, next) {
debug('PUT: /api/quiver/:quiverID/guitar/:guitarID');

try {
Guitar.findByIdAndUpdate(req.params.guitarID, req.params.body, {new: true})
Copy link

@jalleng jalleng Mar 5, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmmmm. What are we passing in here for the updated note? What does req.params reference? How are we passing in the note differently when we do the POST request? (Those are hints) :-)

.then( guitar => res.json(guitar))
.catch( () => next(createError(404, 'not found')));
} catch (err) {
next(createError(400, err.message));
}
});

guitarRouter.delete('/api/quiver/:quiverID/guitar/:guitarID', function(req, res, next) {
debug('DELETE: /api/quiver/:quiverID/guitar/:guitarID');

try {
Guitar.findByIdAndRemove(req.params.guitarID)
.then( () => res.status(204).send('no content'))
.catch( () => next(createError(404, 'not found')));
} catch (err) {
next(createError(400, err.message));
}
});
Loading