Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
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"
}
129 changes: 129 additions & 0 deletions lab-geoff/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@

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

data/player/*.json

### 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.
Empty file added lab-geoff/data/player/.keep
Empty file.
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']);
7 changes: 7 additions & 0 deletions lab-geoff/lib/cors-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
'use strict';

module.exports = function(req, res, next) {
res.append('Access-Control-Allow-Origin', '*');
res.append('Access-Control-Allow-Headers', '*');
next();
};
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();
};
71 changes: 71 additions & 0 deletions lab-geoff/lib/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
'use strict';

const uuid = require('node-uuid');
const Promise = require('bluebird');
const createError = require('http-errors');
const debug = require('debug')('mnp:storage');
const fs = Promise.promisifyAll(require('fs'), {suffix: 'Prom'});

module.exports = exports = {};

exports.createItem = function(collection, item) {
debug('createItem()', item);
if(!collection) return Promise.reject(createError(400, 'collection name not supplied'));
if(!item) return Promise.reject(createError(400, 'missing item to create'));

item.id = item.id || uuid.v4().slice(0,8);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Checkout the shortid npm module. I often use it instead of uuid's because they are prettier. They do have a higher chance of collision though.


let json = JSON.stringify(item);
return fs.writeFileProm(`./data/${collection}/${item.id}.json`, json)
.then( () => item)
.catch( err => Promise.reject(createError(500, err.message)));
};

exports.fetchItem = function(collection, id) {
debug('fetchItem()', collection, id);
if(!collection) return Promise.reject(createError(400, 'collection name not supplied'));
if(!id) return Promise.reject(createError(400, 'missing id'));

return fs.readFileProm(`./data/${collection}/${id}.json`)
.then( data => {
let item = JSON.parse(data.toString());
return item;
})
.catch( err => Promise.reject(createError(404, err.message)));
};

exports.deleteItem = function(collection, id) {
debug('deleteItem()', collection, id);
if(!collection) return Promise.reject(createError(400, 'collection name not supplied'));
if(!id) return Promise.reject(createError(400, 'missing id'));

return fs.unlinkProm(`./data/${collection}/${id}.json`)
.catch( err => Promise.reject(createError(404, err.message)));
};

exports.updateItem = function(collection, id, _item) {
debug('updateItem()',collection,id,_item);
if(!collection) return Promise.reject(createError(400, 'collection name not supplied'));
if(!id) return Promise.reject(createError(400, 'missing id'));

return this.fetchItem(collection, id)
.then( item => {
for(let prop in item) {
if(prop === 'id') continue;
if(_item[prop]) item[prop] = _item[prop];
}
// Calling createItem seems weird here, but we are essentially
// just overwriting the object that was there.
return this.createItem(collection, item);
})
.catch( err => Promise.reject(createError(404, err.message)));
};

exports.listItems = function(collection) {
debug('listItems()');
return fs.readdirProm(`./data/${collection}`)
.then( files => files
.filter( name => name !== '.keep')
.map(name => name.split('.json')[0]))
.catch( err => Promise.reject(createError(404, err.message)));
};
46 changes: 46 additions & 0 deletions lab-geoff/model/player.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
'use strict';

const createError = require('http-errors');
const debug = require('debug')('mnp:player');
const storage = require('../lib/storage.js');

const Player = module.exports = function(name, email) {
debug('Player() constructor');

if(!name || name.length === 0) throw createError(400, 'invalid name');
if(!email || email.length === 0) throw createError(400, 'invalid email');
//TODO: Assert email matches email regex.

this.name = name;
this.email = email;
};

Player.create = function(_player) {
debug('Player.create()', _player);
try {
let player = new Player(_player.name, _player.email);
return storage.createItem('player', player);
} catch (err) {
return Promise.reject(createError(400, err.message));
}
};

Player.update = function(id, player) {
debug('Player.update()', id, player);
return storage.updateItem('player', id, player);
};

Player.fetch = function(id) {
debug('Player.fetch()', id);
return storage.fetchItem('player', id);
};

Player.delete = function(id) {
debug('Player.delete()', id);
return storage.deleteItem('player', id);
};

Player.list = function() {
debug('Player.list()');
return storage.listItems('player');
};
27 changes: 27 additions & 0 deletions lab-geoff/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "12-express-middleware-lab-geoff",
"version": "1.0.0",
"description": "",
"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",
"debug": "^2.4.5",
"express": "^4.14.0",
"http-errors": "^1.5.1",
"morgan": "^1.7.0",
"node-uuid": "^1.4.7"
},
"devDependencies": {
"chai": "^3.5.0",
"mocha": "^3.2.0",
"superagent": "^3.3.1"
}
}
Loading