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 lab-geoff/.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"
}
127 changes: 127 additions & 0 deletions lab-geoff/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@

# Created by https://www.gitignore.io/api/node,macos,vim,windows,linux

### Node ###
node_modules
# Logs
logs
*.log
npm-debug.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

# 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



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


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


### Windows ###
# Windows image file caches
Thumbs.db
ehthumbs.db

# Folder config file
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msm
*.msp

# Windows shortcuts
*.lnk


### 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*
31 changes: 31 additions & 0 deletions lab-geoff/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# MondayNightPinball Resource API

This API currently handles the CRD of CRUD for player objects. Each player has a name and email (for now), and IDs will be auto-assigned. This API uses express for the service and routing layers.

# API

## GET /api/player?id=player_id
Gets a player from the system. Returns application/json of the player object, or 404 if not found.

## POST /api/player
Add a player to the system.
```js
{
name: 'First Last',
email: 'someone@example.com'
}
```
Both `name` and `email` are required in the post body. API expects content type of application/json. Returns a 201 with the newly created player, or a 400 if name or email are missing or not valid.

## PUT /api/player
Update a player
```js
{
name: 'Updated Name',
email: 'updated@example.com'
}
```
Update can include name and/or email. Only supplied values will be updated. Should return a 202 on success, and 404 if the player is not found.

## DELETE /api/player?id=player_id
Removes a player from the system, if found. Returns status 204 on success.
24 changes: 24 additions & 0 deletions lab-geoff/gulpfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict';

const gulp = require('gulp');
const eslint = require('gulp-eslint');
const mocha = require('gulp-mocha');

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

gulp.task('test', function() {
gulp.src('./test/*.js', { read: false })
.pipe(mocha({ reporter: 'spec'}));
//TODO: Try nyan reporter.
});

gulp.task('dev', function() {
gulp.watch(['**/*.js', '!node_modules/**'], ['lint', 'test']);
});

gulp.task('default', ['dev']);
19 changes: 19 additions & 0 deletions lab-geoff/lib/error-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use strict';

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

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

if(err.status) {
debug('user error:',err.name);
res.status(err.status).send(err.name);
return next();
}

debug('server error:',err.name);
err = createError(500, err.message);
res.status(err.status).send(err.name);
next();
};
13 changes: 13 additions & 0 deletions lab-geoff/model/player.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;

// TODO: Q: Is there an Email type? Not sure what mongoose will validate.
const playerSchema = Schema({
name: { type: String, required: true },
email: { type: String, required: true },
timestamp: { type: Date, required: true }
});

module.exports = mongoose.model('player', playerSchema);
29 changes: 29 additions & 0 deletions lab-geoff/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "13-mongo-and-express-api-gws",
"version": "1.0.0",
"description": "Single resource api using express and mongo.",
"main": "index.js",
"scripts": {
"test": "DEBUG='mnp*' mocha",
"start": "DEBUG='mnp*' node start.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bluebird": "^3.4.6",
"body-parser": "^1.15.2",
"cors": "^2.8.1",
"debug": "^2.4.5",
"express": "^4.14.0",
"http-errors": "^1.5.1",
"mongoose": "^4.7.4",
"morgan": "^1.7.0",
"node-uuid": "^1.4.7"
},
"devDependencies": {
"chai": "^3.5.0",
"mocha": "^3.2.0",
"superagent": "^3.3.1"
}
}
51 changes: 51 additions & 0 deletions lab-geoff/route/player-route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
'use strict';

const debug = require('debug')('mnp:player-route');
const Router = require('express').Router;
const jsonParser = require('body-parser').json();
const createError = require('http-errors');

const Player = require('../model/player.js');

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

router.post('/api/player', jsonParser, function(req, res, next) {
debug('POST /api/player',req.body);
//TODO: Move the default timestamping into the model.
req.body.timestamp = Date.now();
new Player(req.body).save()
.then( player => res.status(201).json(player))
.catch( err => {
// NOTE: It sucks that mongoose won't tell us what field is invalid?
err = createError(400, err.name);
next(err);
});
});

router.get('/api/player/:id', function(req, res, next) {
debug('GET /api/player/:id',req.params.id);
Player.findById(req.params.id)
.then( player => res.json(player))
.catch( err => next(createError(404, err.name)) );
});

router.get('/api/player', function(req, res, next) {
debug('GET /api/player');
Player.find({}, { _id: 1})
.then( ids => res.json(ids.map(obj => obj._id)))
.catch(next);
});

router.put('/api/player/:id', jsonParser, function(req, res, next) {
debug('PUT /api/player/:id',req.params.id,req.body);
Player.update({ _id: req.params.id }, req.body)
.then( result => res.status(202).json(result))
.catch(next);
});

router.delete('/api/player/:id', function(req, res, next) {
debug('DELETE /api/player/:id',req.params.id);
Player.findByIdAndRemove(req.params.id)
.then( what => res.status(204).json(what))
.catch( err => next(createError(404, err.name)) );
});
38 changes: 38 additions & 0 deletions lab-geoff/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
'use strict';

const express = require('express');
const debug = require('debug')('mnp:server');
const Promise = require('bluebird');
const mongoose = require('mongoose');

const app = express();
const PORT = process.env.PORT || 4567;

const MONGODB_URI = 'mongodb://localhost/mnp';
mongoose.Promise = Promise;

module.exports = exports = {};

app.use(require('morgan')('dev'));
app.use(require('cors')());
app.use(require('./route/player-route.js'));
app.use(require('./lib/error-middleware.js'));

exports.start = function() {
return new Promise( (resolve, reject) => {
// Q: Is this overkill to force mongoose to connect
// before the app starts listening?
mongoose.connect(MONGODB_URI)
.then( () => {
debug('Mongoose connected:', MONGODB_URI);
})
.then(app.listen(PORT))
.then( () => {
debug('Server up:', PORT);
resolve();
})
.catch( err => reject(err));
});
};

exports.PORT = PORT;
3 changes: 3 additions & 0 deletions lab-geoff/start.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
'use strict';

require('./server.js').start();
Loading