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-zachary/.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-zachary/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@

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

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

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

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Typescript v1 declaration files
typings/

# 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

# dotenv environment variables file
.env


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

### Windows ###
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db

# Folder config file
Desktop.ini

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

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

# Windows shortcuts
*.lnk

# End of https://www.gitignore.io/api/node,osx,windows,linux
45 changes: 45 additions & 0 deletions lab-zachary/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Vanilla Javascript API router w/File Server persistance

This app creates an HTTP server that handles GET, POST, and DELETE to a server-level persistance layer.

# System Requirements

- Terminal.app on macOS or equivalent
- node.js and npm package manager installed


### Installation

Clone the repository to your local server
```sh
https://github.com/zcrumbo/09-vanilla_rest_api_persistence.git
```

Install the dependencies -

```sh
$ npm i
```
[HTTPie](https://httpie.org/) will be required to run the HTTP requests from your terminal window. You will need to install this with [Homebrew][1] on macOS. It is also easier to see the results of all operations by running mocha tests with the command
```sh
$ mocha
```

Start the server

```sh
$ node server.js
```


### Connecting

If you are using HTTPie, in your terminal window, type the following commands, where '3000' would be replaced with your local environment PORT variable, if configured. Commands can only be sent to the api/bike endpoint
```sh
$ http POST :3000/api/bike name='test name' content='test content' #creates a new bike object and writes it to the fileserver, and returns a unique id
$ http GET localhost:8000/api/bike?id=sample-id #returns the name and content of a stored bike object
$ DELETE localhost:8000/api/bike?id=sample-id #deletes the bike file from server storage
```

[1]:https://brew.sh/

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"1b8d9b7e-cafa-4add-9d5e-5a95ba0bec31","name":"test name","content":"test content"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"ba3e0125-7652-4b19-8a3f-957789138f5b","name":"test name","content":"test content"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"d6109482-cd7e-45ea-9eae-44343753edc1","name":"test name","content":"test content"}
23 changes: 23 additions & 0 deletions lab-zachary/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']);
});

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

module.exports = function(req){
return new Promise((resolve, reject) => {
if (req.method === 'POST' || req.method == 'PUT') {
var body = '';
req.on('data', function(data){
body += data.toString();
});

req.on('end', function() {
try{
req.body = JSON.parse(body);
resolve(req);
} catch (err){
console.error(err);
reject(err);
}
});

req.on('error', err =>{
console.error(err);
reject(err);
});
return;
}
resolve();
});
};
9 changes: 9 additions & 0 deletions lab-zachary/lib/parse-url.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
'use strict';

const parse = require('url').parse;

module.exports = function(req){
//return object with url, query string, parameters etc
req.url = parse(req.url, true); //true parameter returns query string as an object
return Promise.resolve(req);
};
19 changes: 19 additions & 0 deletions lab-zachary/lib/response.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use strict';

exports = module.exports = {};

exports.sendText = function(res, status, message){
res.writeHead(status, {
'Content-Type' : 'text/plain'
});
res.write(message);
res.end();
};

exports.sendJSON = function (res, status, data){
res.writeHead(status, {
'Content-Type' : 'application/json'
});
res.write(JSON.stringify(data));
res.end();
};
51 changes: 51 additions & 0 deletions lab-zachary/lib/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
'use strict';

const Promise = require('bluebird');
const parseUrl = require('./parse-url.js');
const parseBody = require('./parse-body.js');
const writeResponse = require('./response.js');

const Router = module.exports = function (){
this.routes = {
GET: {},
POST: {},
PUT: {},
DELETE: {},
};
};

Router.prototype.get = function(endpoint, callback){
this.routes.GET[endpoint] = callback;
};
Router.prototype.post = function(endpoint, callback){
this.routes.POST[endpoint] = callback;
};
Router.prototype.put = function(endpoint, callback){
this.routes.PUT[endpoint] = callback;
};
Router.prototype.delete = function(endpoint, callback){
this.routes.DELETE[endpoint] = callback;
};

Router.prototype.route = function(){
return (req, res) => {
Promise.all([
parseUrl(req),
parseBody(req),
])
.then( () => {
//request is valid, check if route is registered
if (typeof this.routes[req.method][req.url.pathname] === 'function'){
this.routes[req.method][req.url.pathname](req, res);
return;
}
//endpoint not found/route not registered. return 404
writeResponse.sendText(res, 404, 'not found (router.js)');
res.end();
})
.catch( err => { //promise.all fails, url or post body malformed
console.error(err);
writeResponse.sendText(res, 400, 'bad request');
});
};
};
Loading