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-shawn/.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-shawn/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
Created by https://www.gitignore.io/api/macos,node,vim,windows,linux

out.bmp
### 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


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



### 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*
23 changes: 23 additions & 0 deletions lab-shawn/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# **Vanilla HTTP RESTful API**

## **Overview**

This application is a HTTP RESTful API written in vanilla JavaScript. It utilizes the GET, POST, & DELETE methods to fetch, add, and remove files in a file system.

## **How To Use API**
* Clone this repository
* Open a terminal and run `npm i` to install all the application dependencies

### **Run your server**
`node server.js`

In a new terminal window/tab run your HTTP method commands

### **POST Request**
`http POST localhost:[port number]/api/person name='[name]' gender='[gender]'`

### **GET Request**
`http GET localhost:[port number]/api/person?id='[id]'`

### **DELETE Request**
`http DELETE localhost:[port number]/api/person?id='[id]'`
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"1cb81800-c740-11e6-8f4d-b5aaa3bfd81a","name":"test name","gender":"male"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"1ec685a0-c740-11e6-9b41-31efed65bd5c","name":"test name","gender":"male"}
23 changes: 23 additions & 0 deletions lab-shawn/gulpfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'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']);
47 changes: 47 additions & 0 deletions lab-shawn/lib/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
'use strict';

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


module.exports = exports = {};

exports.createInstance = function(schemaName, person){
debug('createInstance');

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

let json = JSON.stringify(person);

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

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

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

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

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

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)));

};
39 changes: 39 additions & 0 deletions lab-shawn/model/person.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'use strict';

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


const Person = module.exports = function(name, gender){
debug('person constructor');

if(!name) throw createError(400, 'expected name');
if(!gender) throw createError(400, 'expected gender');

this.id = uuid.v1();
this.name = name;
this.gender = gender;
};

Person.createPerson = function(_person){
debug('createPerson');

try{
let person = new Person(_person.name,_person.gender);
return storage.createInstance('person', person);
} catch (err){
return Promise.reject(createError(400,err.message));
}
};

Person.fetchPerson = function(id){
debug('fetchPerson');
return storage.fetchInstance('person',id);
};

Person.deletePerson = function(id){
debug('deletePerson');
return storage.deleteInstance('person',id);
};
32 changes: 32 additions & 0 deletions lab-shawn/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "lab-shawn",
"version": "1.0.0",
"description": "",
"main": "server.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "DEBUG='person*' node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bluebird": "^3.4.6",
"body-parser": "^1.15.2",
"express": "^4.14.0",
"http-errors": "^1.5.1",
"morgan": "^1.7.0",
"node-uuid": "^1.4.7"
},
"devDependencies": {
"chai": "^3.5.0",
"gulp": "^3.9.1",
"gulp-eslint": "^3.0.1",
"gulp-mocha": "^3.0.1",
"mocha": "^3.2.0",
"superagent": "^3.3.0"
}
}
54 changes: 54 additions & 0 deletions lab-shawn/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
'use strict';

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

const app = express();
const Person = require('./model/person.js');
const PORT = process.env.PORT || 3000;

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

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

Person.createPerson(req.body)
.then(person => res.json(person))
.catch(err => next(err));
});

app.get('/api/person', function(req,res,next){
debug('GET: /api/person');

Person.fetchPerson(req.query.id)
.then(person => res.json(person))
.catch(err => next(err));
});

app.delete('/api/person', function(req,res,next){
debug('DELETE: /api/person');

Person.deletePerson(req.query.id)
.then(() => res.status(204).send())
.catch(err => next(err));
});

//eslint-disable-next-line
app.use(function(err,req,res,next){
debug('error middleware');

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

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

app.listen(PORT, function(){
console.log(`served on port: ${PORT}`);
});
Loading