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"
}
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
60 changes: 0 additions & 60 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,60 +0,0 @@
![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
37 changes: 37 additions & 0 deletions lib/error-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

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

module.exports = function(err, req, res, next) {
console.error(err.message);
console.error(err.name);

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

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

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/pokemon.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'use strict';

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

const pokemonSchema = Schema({
name: {type: String, required: true},
type: {type: String, required: true},
gen: {type: String, require: true},
timestamp: {type: Date, required: true}
});

module.exports = mongoose.model('pokemon', pokemonSchema);
38 changes: 38 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"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",
"directories": {
"test": "test"
},
"scripts": {
"test": "DEBUG='pokemon*' mocha",
"start": "DEBUG='pokemon*' node server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Loaye/13-mongodb.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/Loaye/13-mongodb/issues"
},
"homepage": "https://github.com/Loaye/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",
"mongoose": "^4.11.5",
"morgan": "^1.8.2"
},
"devDependencies": {
"chai": "^4.1.0",
"mocha": "^3.5.0",
"superagent": "^3.5.2"
}
}
53 changes: 53 additions & 0 deletions route/pokemon-route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
'use strict';

const Router = require('express').Router;
const jsonParser = require('body-parser').json();
const debug = require('debug')('pokemon:pokemon-router');
const Pokemon = require('../model/pokemon.js');
const pokemonRouter = module.exports = new Router();

pokemonRouter.post('/api/pokemon', jsonParser, function (req, res, next) {
debug('POST: /api/pokemon');

req.body.timestamp = new Date();
new Pokemon(req.body).save()
.then(pokemon => res.json(pokemon))
.catch(next);
});

pokemonRouter.get('/api/pokemon/:id', function (req, res, next) {
debug('GET: /api/pokemon/:id');
Pokemon.findById(req.params.id)
.then(pokemon => res.json(pokemon))
.catch(next);
});

pokemonRouter.put('/api/pokemon/:id', jsonParser, (req, res, next) => {
debug('PUT /api/pokemons/:id');

if (Object.keys(req.body).length === 0) {
Pokemon.findById(req.params.id)
.then(pokemon => {
res.status(400);
res.json(pokemon);
})
.catch(next);
return;
}

let options = {
runValidator: true,
new: true,
};

Pokemon.findByIdAndUpdate(req.params.id, req.body, options)
.then(pokemon => res.json(pokemon))
.catch(next);
});

pokemonRouter.delete('/api/pokemon/:id', function (req, res, next) {
debug('GET: /api/pokemon/:id');

Pokemon.findByIdAndRemove(req.params.id)
.catch(next);
});
26 changes: 26 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict';

const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const Promise = require('bluebird');
const mongoose = require('mongoose');
const debug = require('debug')('pokemon:server');
const pokemonRouter = require('./route/pokemon-route.js');
const errors = require('./lib/error-middleware.js');

const app = express();
const PORT = process.env.PORT || 3000;
const MONGODB_URI = 'mongodb://localhost/pokemonlist';

mongoose.Promise = Promise;
mongoose.connect(MONGODB_URI);

app.use(cors());
app.use(morgan('dev'));
app.use(pokemonRouter);
app.use(errors);

app.listen(PORT, () => {
debug(`listening on ${PORT}`);
});
Loading