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-megan/.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"
}
147 changes: 147 additions & 0 deletions lab-megan/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
Skip to content
This repository
Search
Pull requests
Issues
Gist
@meganreardon
Watch 5
Star 1
Fork 3 codefellows/seattle-javascript-401d12
Code Issues 0 Pull requests 0 Projects 0 Wiki Pulse Graphs
Branch: master Find file Copy pathseattle-javascript-401d12/02-build_automation_and_dependency_management/lecture/demo/hello-world-gulp/.gitignore
b2d8bee 41 minutes ago
@bnates bnates added lecture 2 material
1 contributor
RawBlameHistory
128 lines (94 sloc) 1.85 KB
# Created by https://www.gitignore.io/api/node,vim,macos,linux,windows

node_modules/

### Node ###
# Logs
logs
*.log
npm-debug.log*
data

# 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



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


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


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


### 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
Contact GitHub API Training Shop Blog About
© 2016 GitHub, Inc. Terms Privacy Security Status Help
44 changes: 44 additions & 0 deletions lab-megan/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
### ABOUT THIS PROJECT

This is a simple Express router built as part of the Code Fellows 401 JavaScript class. It uses Express to handle middleware and routing, in this case I'm keeping track of hats with a color and style.

### HOW TO GET THE API RUNNING

Clone this repository.
```JavaScript
cd lab-megan

npm i
```
To get needed Node dependencies.

In one terminal window:
```JavaScript
nmp run start
```

### HOW TO USE THE API

With this API you can create, view and delete the records of various hat. To do so get the server running in a terminal window and open a second terminal window and do the following

- To create a hat
`http POST localhost:3000/api/hat color='<a color>' style='<a style>'`
This will return your color, style and a unique id.

Note: If your server shows it is running on a different port please use that one instead.


- To view the record of a hat
`http localhost:3000/api/hat?id=<the id of a known hat>`
This will return the color and style of the requested id.

- To delete the record of a hat
`http DELETE localchost:3000/api/hat?id=<the id of a known hat>`
This will return a 204 message to confirm any record of the had has been deleted.

### HOW TO INCLUDE IN YOUR PROJECT

```JavaScript
npm i -D chai mocha superagent
npm run test
```
24 changes: 24 additions & 0 deletions lab-megan/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('test', function() {
gulp.src('./test/*-test.js', { read: false })
.pipe(mocha({ reporter: 'spec'}));
});

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

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

gulp.task('default', ['dev']);
7 changes: 7 additions & 0 deletions lab-megan/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();
};
21 changes: 21 additions & 0 deletions lab-megan/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')('hat: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();
};
58 changes: 58 additions & 0 deletions lab-megan/lib/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
'use strict';

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

module.exports = exports = {};

exports.createItem = function(schemaName, item){
debug('createItem');

if (!schemaName) return Promise.reject(createError(400, 'expected schema name'));
if (!item) return Promise.reject(createError(400, 'expected item'));

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

exports.fetchItem = function(schemaName, id){
debug('fetchItem');

if (!schemaName) return Promise.reject(createError(400, 'expected schema name'));
if (!id) return Promise.reject(createError(400, 'expected id'));

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

exports.deleteItem = function(schemaName, id) {
debug('deleteItem');

if (!schemaName) return Promise.reject(createError(400, 'expected schema name'));
if (!id) return Promise.reject(createError(400, 'expected id'));

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

exports.availIDs = function(schemaName) {
debug('availIDs'); // NOTE: I added this line

if (!schemaName) return Promise.reject(createError(400, 'expected schema name')); // NOTE: I added this line

return fs.readdirProm(`${__dirname}/../data/${schemaName}`)
.then ( files => files.map(color => color.split('.json')[0]))
.catch( err => Promise.reject(createError(404, err.message)));
};
57 changes: 57 additions & 0 deletions lab-megan/model/hat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
'use strict';

const uuid = require('node-uuid');
const createError = require('http-errors');
const debug = require('debug')('hat:hat');
const storage = require('../lib/storage.js');

const Hat = module.exports = function(color, style) {
debug('hat constructor');

if (!color) throw createError(400, 'expected color');
if (!style) throw createError(400, 'expected style');

this.id = uuid.v1();
this.color = color;
this.style = style;
};

Hat.createHat = function(_hat) {
debug('createHat');

try {
let hat = new Hat(_hat.color, _hat.style);
return storage.createItem('hat', hat);
} catch (err) {
return Promise.reject(createError(400, 'err.message'));
}
};

Hat.fetchHat = function(id) {
debug('fetchHat');
return storage.fetchItem('hat', id);
};

Hat.updateHat = function(id, _hat) {
debug('updateHat');

return storage.fetchItem('hat', id)
.catch( err => Promise.reject(createError(404, err.message)))
.then( hat => {
for (var prop in hat) {
if (prop === 'id') continue;
if (_hat[prop]) hat[prop] = _hat[prop];
}
return storage.createItem('hat', hat);
});
};

Hat.deleteHat = function(id) {
debug('deleteHat');
return storage.deleteItem('hat', id);
};

Hat.fetchIDs = function() {
debug('fetchIDs');
return storage.availIDs('hat');
};
Loading