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
5 changes: 5 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
**/node_modules/*
**/vendor/*
**/*.min.js
**/coverage/*
**/build/*
26 changes: 26 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"env": {
"browser": true,
"node": true,
"commonjs": true,
"jest": true,
"es6": true
},
"globals": {
"err": true,
"req": true,
"res": true,
"next": true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"no-console": "off",
"indent": [ "error", 2 ],
"quotes": ["error", "single", { "allowTemplateLiterals": true }],
"comma-dangle": ["error", "always-multiline"],
"semi": [ "error", "always" ]
}
}
145 changes: 145 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
# 401 JS
db
.env
temp
build

# Created by https://www.gitignore.io/api/vim,osx,node,linux,windows
### 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

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

### 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/vim,osx,node,linux,windows
11 changes: 11 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict';

// load environment
require('dotenv').config();

// load dependencies
const server = require('./lib/server.js');

// start server
server.start(process.env.PORT, () =>
console.log('server up ::', process.env.PORT));
32 changes: 32 additions & 0 deletions lib/request-parser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
'use strict';

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

// a promise is an object that manages sync and async callbacks
// with a consistant interface
// use then and catch methods to handle success and failures
module.exports = (req) => {
return new Promise((resolve, reject) => {
req.url = url.parse(req.url);
req.url.query = queryString.parse(req.url.query);

if(!(req.method === 'POST' || req.method === 'PUT'))
return resolve(req);

let text = '';
// ONLY PARSER THE POST OR PUT REQUEST BODIES
req.on('data', (buffer) => {
text += buffer.toString();
});
req.on('end', () => {
if (!text) text = '{}';
try {
req.body = JSON.parse(text);
resolve(req);
} catch (err) {
reject(err);
}
});
});
};
133 changes: 133 additions & 0 deletions lib/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
'use strict';

const http = require('http');
const requestParser = require('./request-parser.js');
const cowsay = require('cowsay');

const app = http.createServer((req, res) => {
//console.log('got a request!')
//console.log('req.method', req.method)
//console.log('req.headers', req.headers)

requestParser(req)
.then(req => {
// handle routes
const pathname = req.url.pathname;
console.log('pathname:', pathname);
console.log(req.headers);
if(req.method === 'GET' && req.url.pathname === '/'){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(`<!DOCTYPE html>
<html>
<head> <title> cowsay </title> </head>
<body>
<li><a href="/cowsay">cowsay</a></li>
<h2> This is my cowsay project </h2>
</body>
</html>`);
res.end();
return; // break out of the (req, res) => {} callback
}

if(req.method === 'GET' && req.url.pathname === '/cowsay'){
console.log('query:', req.url.query);
var text = req.url.query.text;
if(text === undefined || text === ''){
text = 'I need something good to say';
}
let cow = cowsay.say({text: text});
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(`<!DOCTYPE html>
<html>
<head> <title> cowsay </title> </head>
<body>
<pre>
${cow}
</pre>
</body>
</html>`);
res.end();
return;
}

if(req.method === 'GET' && req.url.pathname === '/api/cowsay'){
let responseBody = {};
let statusCode = 200;
text = req.url.query.text;
console.log('query:', req.url.query);
if (JSON.stringify(req.url.query) === JSON.stringify({})) {
console.log('empty');
statusCode = 400;
responseBody = {
error: 'invalid request: query is required',
};
} else if (text === undefined || text === '') {
const inputError = {error: 'invalid request: text query required'};
responseBody = inputError;
statusCode = 400;
} else {
let cow = cowsay.say({text: text});
responseBody = {
content: cow,
};
}
res.writeHead(statusCode, {'Content-Type': 'application/json'});
res.write(JSON.stringify(responseBody));
res.end();
return; // break out of the (req, res) => {} callback
}

if(req.method === 'POST' && req.url.pathname === '/api/cowsay'){
let responseBody = {};
let statusCode = 200;
if (JSON.stringify(req.body) === JSON.stringify({})) {
statusCode = 400;
responseBody = {
error: 'invalid request: body required',
};
} else if (req.body.text === undefined || req.body.text === ''){
responseBody = {
error: 'invalid request: text required',
};
statusCode = 400;
} else {
let cow = cowsay.say({text: req.body.text});
responseBody = {
content: cow,
};
}
res.writeHead(statusCode, {'Content-Type': 'application/json'});
res.write(JSON.stringify(responseBody));
res.end();
return; // break out of the (req, res) => {} callback
}

if(req.method === 'POST' && req.url.pathname === '/echo'){
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(req.body));
res.end();
return; // break out of the (req, res) => {} callback
}

// 404 for any request to a non route
// respond to the client
res.writeHead(404, {
'Content-Type': 'text/plain',
});
res.write(`resource ${req.url.pathname} not found!`);
res.end();
})
.catch(err => {
console.log(err);
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.write('bad request');
res.end();
});
// register routes
});

// export interface
module.exports = {
start: (port, callback) => app.listen(port, callback),
stop: (callback) => app.close(callback),
};
Loading