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

Lab luis #7

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
5 changes: 5 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
**/node_modules/*
**/vendor/*
**/*.min.js
**/coverage/*
**/build/*
16 changes: 16 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"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
},
"extends": "eslint:recommended"
}
136 changes: 136 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# Created by https://www.gitignore.io/api/osx,vim,node,macos,windows

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

# Icon must end with two \r

# Thumbnails

# Files that might appear in the root of a volume

# Directories potentially created on remote AFP share

### Vim ###
# swap
[._]*.s[a-v][a-z]
[._]*.sw[a-p]
[._]s[a-v][a-z]
[._]sw[a-p]
# session
Session.vim
# temporary
.netrwhist
*~
# auto-generated tag files
tags

### 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/osx,vim,node,macos,windows
86 changes: 26 additions & 60 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,60 +1,26 @@
![CF](https://camo.githubusercontent.com/70edab54bba80edb7493cad3135e9606781cbb6b/687474703a2f2f692e696d6775722e636f6d2f377635415363382e706e67) 13: Single Resource Mongo and Express API
===

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

## Learning Objectives
* students will be able to work with the MongoDB database management system
* students will understand the primary concepts of working with a NoSQL database management system
* students will be able to create custom data models *(schemas)* through the use of mongoose.js
* students will be able to use mongoose.js helper methods for interacting with their database persistence layer

## Requirements
#### 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 resource **model** of your choice that uses `mongoose.Schema` and `mongoose.model`
* use the `body-parser` express middleware to parse the `req` body on `POST` and `PUT` requests
* use the npm `debug` module to log the functions and methods that are being used in your application
* use the express `Router` to create a route for doing **RESTFUL CRUD** operations against your _model_

## Server Endpoints
### `/api/resource-name`
* `POST` request
* should pass data as stringifed JSON in the body of a post request to create a new resource

### `/api/resource-name/:id`
* `GET` request
* should pass the id of a resource through the url endpoint to get a resource
* **this should use `req.params`, not querystring parameters**
* `PUT` request
* should pass data as stringifed JSON in the body of a put request to update a pre-existing resource
* `DELETE` request
* should pass the id of a resource though the url endpoint to delete a resource
* **this should use `req.params`**

### Tests
* create a test that will ensure that your API returns a status code of 404 for routes that have not been registered
* create a series of tests to ensure that your `/api/resource-name` endpoint responds as described for each condition below:
* `GET` - test 200, returns a resource with a valid body
* `GET` - test 404, respond with 'not found' for valid requests made with an id that was not found
* `PUT` - test 200, returns a resource with an updated body
* `PUT` - test 400, responds with 'bad request' if no request body was provided
* `PUT` - test 404, responds with 'not found' for valid requests made with an id that was not found
* `POST` - test 400, responds with 'bad request' if no request body was provided
* `POST` - test 200, returns a resource for requests made with a valid body

### Bonus
* **2pts:** a `GET` request to `/api/resource-name` should return an array of stored resources
![cf](https://i.imgur.com/7v5ASc8.png) 13: MongoDB
======

## Installation

Run npm -i to install dependencies

## Usage

You can query "Airport" resources as shown below:

GET '/api/airport/:id' - to query a specific airport

POST '/api/airport' [name, iata, city] - to post a new airport

PUT '/api/airport/:id' [name, iata, city] - to update an airport

The API handles for errors so it should prevent a user from making too many mistakes.

## Credits

Luis Manzo

## License

MIT
21 changes: 21 additions & 0 deletions lib/error-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')('note:error-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();
};
13 changes: 13 additions & 0 deletions model/airport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const createError = require('http-errors');

//require later
const airportSchema = new Schema({
name : { type: String, required: true },
iata : { type: String, required: false },
city : { type: String, required: false }
});


module.exports = mongoose.model('Airport', airportSchema);
36 changes: 36 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "13-mongodb",
"version": "1.0.0",
"description": "![CF](https://camo.githubusercontent.com/70edab54bba80edb7493cad3135e9606781cbb6b/687474703a2f2f692e696d6775722e636f6d2f377635415363382e706e67) 13: Single Resource Mongo and Express API ===",
"main": "server.js",
"scripts": {
"test": "DEBUG='airport*' node_modules/mocha/bin/mocha",
"start": "DEBUG='airport*' node server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/ctcrnitv/13-mongodb.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/ctcrnitv/13-mongodb/issues"
},
"homepage": "https://github.com/ctcrnitv/13-mongodb#readme",
"dependencies": {
"bluebird": "^3.5.0",
"body-parser": "^1.17.2",
"cors": "^2.8.4",
"debug": "^2.6.8",
"express": "^4.15.3",
"http-errors": "^1.6.1",
"mongoose": "^4.11.5",
"morgan": "^1.8.2"
},
"devDependencies": {
"chai": "^4.1.0",
"mocha": "^3.5.0",
"superagent": "^3.5.2"
}
}
57 changes: 57 additions & 0 deletions route/airport_route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const Router = require('express').Router;
const jsonParser = require('body-parser').json();
const debug = require('debug')('airport:airport-router');
const Airport = require('../model/airport.js');
const airportRouter = module.exports = new Router();
const createError = require('http-errors');

airportRouter.post('/api/airport', jsonParser, function (req, rsp, next) {
debug('POST: /api/airport');
if (Object.keys(req.body).length === 0) {
return next(createError(400));
}
new Airport(req.body).save()
.then(airport => rsp.json(airport))
.catch((err) => {
debug('error: ', err.status);
next(createError(404));
});
});

airportRouter.put('/api/airport/:id', jsonParser, function (req, rsp, next) {
debug('PUT: /api/airport/:id');

if (Object.keys(req.body).length === 0) {
return next(createError(400));
}

Airport.findByIdAndUpdate(req.params.id, req.body)
.then((airport) => {
return rsp.json(airport);
})
.catch((err) => {
next();
})
})

airportRouter.get('/api/airport/:id', function (req, rsp, next) {
debug('GET: /api/airport');
Airport.findById(req.params.id)
.then((airport) => {
return rsp.json(airport);
})
.catch((err) => {
next();
})
})

airportRouter.delete('/api/airport/:id', function (req, rsp, next) {
debug('DELETE: /api/airport');
Airport.findByIdAndRemove(req.params.id)
.then((done) => {
done();
})
.catch((err) => {
next();
})
})
Loading