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

lab14-Jeremiah 11 Test Passing #8

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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"
}
93 changes: 93 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# Created by https://www.gitignore.io/api/node,osx,windows,linux
### Linux ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# 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,linux
35 changes: 15 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,24 +1,19 @@
![CF](https://camo.githubusercontent.com/70edab54bba80edb7493cad3135e9606781cbb6b/687474703a2f2f692e696d6775722e636f6d2f377635415363382e706e67) Lab 14 - Mongo & Express Two Resource API
) Lab 14 - Mongo & Express Two Resource API
===

## To Submit this Assignment
* Fork this repository
* Write all of your code in a directory named `lab-` + `<your name>` **e.g.** `lab-brian`
* 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
* Created `GET`, `POST`, `PUT`, and `DELETE` routes for your newly added resource
* Tested this application to ensure that it meets the standard criteria of a working **full CRUD** REST API
* Used `populate` in the `get()` route logic your `/api/library/:id` route to populate the associated property used to house related resources

## Include
* `package.json`
* `.eslintrc`
* `gulpfile.js`
* `.gitignore`
* `README.md`
## How to Use
* clone down this repository by copying the link and running the command:
$ git clone (link here)

## Description
* Continue working on the `express` and `mongoDB` REST API that you started yesterday
* Include an additional resource that contains a "relationship" to the single resource that has already been created
* Create `GET`, `POST`, `PUT`, and `DELETE` routes for your newly added resource
* Test your application to ensure that it meets the standard criteria of a working **full CRUD** REST API
* Use `populate` in the `get()` route logic your `/api/new-resource-name/:id` route to populate the associated property used to house related resources **(ex: `List.findById(req.params.id).populate('notes')`)**
* run command to get all needed dependencies:
$ npm i

* to test routes, run the command:
$ npm start

* use POST, GET, PUT, and DELETE routes to create, read, update, and or destroy a new journal
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', 'test']);
});

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')('car: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;
}
debug('server error');
err = createError(500, err.message);
res.status(err.status).send(err.name);
next();
};
12 changes: 12 additions & 0 deletions model/car.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 carSchema = Schema ({
make: { type: String, required: true },
model: { type: String, required: true },
lotID: { type: Schema.Types.ObjectId, required: true }
});

module.exports = mongoose.model('car', carSchema);
36 changes: 36 additions & 0 deletions model/lot.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';

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

const Car = require('./car.js');

const lotSchema = Schema({
name: { type: String, required: true },
timestamp: { type: Date, required: true },
cars: [{ type: Schema.Types.ObjectId, ref: 'car' }]
Copy link

Choose a reason for hiding this comment

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

This can be confusing. Good job referencing the 'car' correctly here.

});

const Lot = module.exports= mongoose.model( 'lot', lotSchema);

Lot.findByIdAndAddCar = function(id, car) {
debug('findByIdAndAddCar');

return Lot.findById(id)
.catch( err => Promise.reject(createError(404, err.message)))
.then( lot => {
car.lotID = lot._id;
this.tempLot = lot;
return new Car(car).save();
})
.then( car => {
this.tempLot.cars.push(car._id);
this.tempCar = car;
return this.tempLot.save();
})
.then( () => {
return this.tempCar;
});
};
36 changes: 36 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"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",
"scripts": {
"test": "DEBUG='car*' ./node_modules/mocha/bin/mocha",
"start": "DEBUG='car*' node server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/jtwalters25/14-mongo_express_two_resource_api.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/jtwalters25/14-mongo_express_two_resource_api/issues"
},
"homepage": "https://github.com/jtwalters25/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-error": "0.0.6",
"mongoose": "^4.8.5",
"morgan": "^1.8.1"
},
"devDependencies": {
"chai": "^3.5.0",
"mocha": "^3.2.0",
"superagent": "^3.5.0"
}
}
34 changes: 34 additions & 0 deletions route/car-route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const Router = require('express').Router;
const jsonParser = require('body-parser').json();
const createError = require('http-errors');
const Lot = require('../model/lot.js');
const Car = require('../model/car.js');
const debug = require('debug')('car:car-router');
const carRouter = module.exports = new Router();

carRouter.post('/api/lot/:lotID/car', jsonParser, function(req, res, next) {
debug('POST: api/lot/:lotID/car');

Lot.findByIdAndAddCar(req.params.lotID, req.body)
.then( car => res.json(car))
.catch( err => next(createError(404, err.message)));
Copy link

Choose a reason for hiding this comment

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

Good job creating the error to send back.

});

carRouter.get('/api/car/:id', function(req, res, next){
debug('GET: /api/car/:id');

Car.findById(req.params.id)
.then( car => res.json(car))
.catch( err => next(createError(404, err.message)));
});

carRouter.put('/api/car/:id', jsonParser, function(req, res, next){
debug('PUT: /api/car/:id');

Car.findByIdAndUpdate(req.params.id, req.body, { new: true })
.then( car => res.json(car))
.catch( err => {
if ( err.name === 'ValidationError') return next(err);
next(createError(404, err.message));
});
});
37 changes: 37 additions & 0 deletions route/lot-route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

const Router = require('express').Router;
const jsonParser = require('body-parser').json();
const createError = require('http-errors');
const debug = require('debug')('car:lot-router');
const Lot = require('../model/lot.js');
const lotRouter = module.exports = new Router();

lotRouter.post('/api/lot', jsonParser, function(req, res, next) {
req.body.timestamp = new Date();
new Lot(req.body).save()
.then( lot => res.json(lot))
.catch(next);
});

lotRouter.get('/api/lot/:id', function(req, res, next) {
Lot.findById(req.params.id)
.populate('cars')
Copy link

Choose a reason for hiding this comment

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

Magic!

.then( lot => res.json(lot))
.catch( err => next(createError(404, err.message)));
});

lotRouter.put('/api/lot/:id', jsonParser, function(req, res, next){
Lot.findByIdAndUpdate(req.params.id, req.body, { new: true })
.then( lot => res.json(lot))
.catch( err => {
if ( err.name === 'ValidationError') return next(err);
next(createError(404, err.message));
});
});

lotRouter.delete('/api/lot/:id', function(req, res, next) {
Lot.findByIdAndRemove(req.params.id)
.then( () => res.status(204).send())
.catch( err => next(createError(404, err.message)));
});
Loading