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

## DELETE /api/player?id=player_id
Removes a player from the system, if found.
Empty file added lab-geoff-11/data/player/.keep
Empty file.
24 changes: 24 additions & 0 deletions lab-geoff-11/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']);
40 changes: 40 additions & 0 deletions lab-geoff-11/lib/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
'use strict';

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

module.exports = exports = {};

exports.createItem = function(collection, 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);

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) {
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) {
if(!collection) return Promise.reject(createError(400, 'collection name not supplied'));
if(!id) return Promise.reject(createError(400, 'missing id'));

//TODO: Wrap the promise then and catch for better messaging?
return fs.unlinkProm(`./data/${collection}/${id}.json`);
};
36 changes: 36 additions & 0 deletions lab-geoff-11/model/player.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';

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

const storage = require('../lib/storage.js');

function Player(name, email) {
debug(`new player, name=${name} email=${email}`);

if(!name) throw createError(400, 'missing name param');
if(!email) throw createError(400, 'missing email param');
this.name = name;
this.email = email;
}

Player.create = function(_player) {
debug('create');

//NOTE: We could try the player constructor, but
// we are catching errors down the call stack.
let player = new Player(_player.name, _player.email);
return storage.createItem('player', player);
};

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

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

module.exports = Player;
40 changes: 40 additions & 0 deletions lab-geoff-11/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"name": "templates",
"version": "1.0.0",
"description": "Base files for node.js projects",
"main": "index.js",
"scripts": {
"test": "gulp test",
"start": "DEBUG='mnp*' node server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/geoffsimons/templates.git"
},
"keywords": [
"nodejs",
"template"
],
"author": "Geoff Simons",
"license": "ISC",
"bugs": {
"url": "https://github.com/geoffsimons/templates/issues"
},
"homepage": "https://github.com/geoffsimons/templates#readme",
"devDependencies": {
"chai": "^3.5.0",
"gulp": "^3.9.1",
"gulp-eslint": "^3.0.1",
"gulp-mocha": "^3.0.1",
"superagent": "^3.3.0"
},
"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"
}
}
55 changes: 55 additions & 0 deletions lab-geoff-11/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
'use strict';

const express = require('express');
const morgan = require('morgan');
const createError = require('http-errors');
const parseJSON = require('body-parser').json();
const debug = require('debug')('mnp:server');

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

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

app.use(morgan('dev'));

app.post('/api/player', parseJSON, function(req, res, next) {
debug('POST: /api/player');
debug('req.body:', req.body);
Player.create(req.body)
.then( player => res.json(player))
.catch( err => next(err));
});

app.get('/api/player', function(req, res, next) {
debug('GET: /api/player id:', req.query.id);
Player.fetch(req.query.id)
.then( player => res.json(player))
.catch( err => next(err));
});

app.delete('/api/player', function(req, res, next) {
debug('DELETE: /api/player id:', req.query.id);
Player.delete(req.query.id)
.then( () => {
res.status(204).send('');
})
.catch( err => next(err));
});

app.use(function(err, req, res, next) {
debug('error middleware');
console.error(err.message);

if(err.status) {
res.status(err.status).send(err.message);
return;
}

err = createError(500, err.message);
res.status(err.status).send(err.name);
});

app.listen(PORT, () => {
debug('server up:', PORT);
});
Loading