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-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"
}
127 changes: 127 additions & 0 deletions lab-geoff/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@

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

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

The cowsay module is a fun module for wrapping text.

# How to install

```sh
git clone https://github.com/geoffsimons/07-vanilla-http-server.git
npm i
```
- To startup the server:
```sh
node server.js
```

# API

This server follows RESTful ideology, with the following routes:
* GET /
--Get a greeting as text/plain
* GET /cowsay?text=Something+to+say[&f=<cow_name>]
- `text` should be a URL encoded string to wrap
- `f` is what cow you want to have speak
* POST /cowsay
```js
{
text: 'Something to say (REQUIRED)',
f: 'beavis.zen'
}
```
See the cowsay docs for more cow names.
https://github.com/piuccio/cowsay/tree/master/cows
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']);
17 changes: 17 additions & 0 deletions lab-geoff/lib/parse-body.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use strict';

module.exports = function(req, callback) {
req.on('data', data => {
req.body = req.body || '';
req.body += data.toString();
});

req.on('end', () => {
try {
req.body = JSON.parse(req.body);
callback(null, req.body);
} catch(err) {
callback(err);
}
});
};
45 changes: 45 additions & 0 deletions lab-geoff/model/router-constructor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
'use strict';

function Router() {
this.routes = [];
}

Router.prototype.add = function(method, path, handler) {
var found = this.routes.find(function(route) {
//TODO: Add support for regex and/or glob specs
return (route.method == method && route.path == path);
});
if(found) {
//TODO: make a test that sets a route more than once
//Update existing route's handler.
found.handler = handler;
return found;
}
this.routes.push({
method: method,
path: path,
handler: handler
});
};

Router.prototype.find = function(method, path) {
var found = this.routes.find(function(route) {
return (route.method == method && route.path == path);
});
if(found) return found.handler;
};

Router.prototype.handle = function(req, res, next) {
var handler = this.find(req.method, req.url.pathname);
if(handler) return handler(req, res);

if(next) return next(req, res);

//Without a next handler, what can we do?
res.err({ status: 404, statusMessage: 'route not found'});
};

module.exports = exports = {};
exports.Router = Router;

//TODO: implement Array.prototype.find to see if I can match functionality
32 changes: 32 additions & 0 deletions lab-geoff/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "templates",
"version": "1.0.0",
"description": "Base files for node.js projects",
"main": "index.js",
"scripts": {
"test": "gulp test"
},
"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"
},
"dependencies": {
"cowsay": "^1.1.9"
}
}
34 changes: 34 additions & 0 deletions lab-geoff/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'use strict';

const cowsay = require('cowsay');

const Router = require('./model/router-constructor.js').Router;
const router = new Router();

router.add('GET', '/', function(req, res) {
res.send('hello from my server!');
});

function say(params, res) {
let text = params.text;
if(!text || text.length == 0) {
res.status = 400;
res.statusMessage = 'bad request';
return res.send(cowsay.say({ text: 'bad request' }));
}
let msg = cowsay.say({
text: text,
f: params.f || 'beavis.zen'
});
res.send(msg);
}

router.add('GET', '/cowsay', function(req, res) {
say(req.url.query, res);
});

router.add('POST', '/cowsay', function(req, res) {
say(req.body, res);
});

module.exports = router;
55 changes: 55 additions & 0 deletions lab-geoff/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
'use strict';

const http = require('http');
const url = require('url');
const querystring = require('querystring');

const PORT = process.env.PORT || 5555;

const router = require('./router.js');
const parseBody = require('./lib/parse-body.js');

//TODO: Q: Should we start using (req, res) => ?
const server = http.createServer(function(req, res) {
req.url = url.parse(req.url);
req.url.query = querystring.parse(req.url.query);

//I'm attaching a couple of utility methods to res
res.send = function(msg) {
res.writeHead(res.status || 200, res.statusMessage || 'OK', res.headers);

console.log('about to send:', msg);
res.write(msg + '\n');
res.end(); //After this, no more writes allowed!
console.log('...done sending');
};

res.json = function(obj) {
res.headers['Content-Type'] = 'application/json';
this.send(JSON.stringify(obj, null, 2));
};

res.err = function(err) {
res.status = err.status || 500;
res.statusMessage = err.statusMessage || 'Internal server error';

this.json({ error: err });
};

res.headers = {
'Content-Type': 'text/plain'
};

if(req.method === 'POST') {
return parseBody(req, (err, body) => {
if(err) return res.err(err);
console.log('parsed body:',body);
router.handle(req, res);
});
}
router.handle(req, res);
});

server.listen(PORT, () => {
console.log('cowsay server up', PORT);
});