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 lab-ron/.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 lab-ron/.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" ]
}
}
70 changes: 70 additions & 0 deletions lab-ron/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Created by https://www.gitignore.io/api/osx,linux,node,vim

### OSX ###
.DS_Store
.AppleDouble
.LSOverride

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


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

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# 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 REPL history
.node_repl_history

### Vim ###
# swap
[._]*.s[a-w][a-z]
[._]s[a-w][a-z]
# session
Session.vim
# temporary
.netrwhist
*~

# auto-generated tag files
tags

###### Personal
.tern-project
.env
temp
2 changes: 2 additions & 0 deletions lab-ron/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# http server

41 changes: 41 additions & 0 deletions lab-ron/__test__/server.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use strict';

let apiURL = `http://localhost:3000`;

const superagent = require('superagent');
describe('POST /api/cowsay', () => {
test('200 OK returns cowsay message', () => {
return superagent.post(`${apiURL}/api/cowsay`)
.send({
text: 'hello world',
})
.then(res => {
console.log('HELLO WORLD', res.body);
expect(res.status).toEqual(200);
expect(res.body).toEqual({ message: ` _____________\n< hello world >\n -------------\n \\ ^__^\n \\ (oo)\\_______\n (__)\\ )\\/\\\n ||----w |\n || ||` }
);
});
});

test('400 Bad Request', () => {
return superagent.post(`${apiURL}/api/cowsay`)
.set({ 'Content-Type': 'application/json' })
.send('{')
.then(Promise.reject)
.catch(res => {
expect(res.status).toEqual(400);
expect(res.response.text).toEqual('bad request');
});
});

test('404 Not found', () => {
let tempPath = 'lulwat';
return superagent.get(`${apiURL}/${tempPath}`)
.then(Promise.reject)
.catch(res => {
expect(res.status).toEqual(404);
expect(res.response.text).toEqual(`resource /${tempPath} not found!`);
});
});

});
11 changes: 11 additions & 0 deletions lab-ron/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));
29 changes: 29 additions & 0 deletions lab-ron/lib/request-parser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use strict';

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


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 = '';
req.on('data', (buffer) => {
text += buffer.toString();
});

req.on('end', () => {
try {
req.body = JSON.parse(text);
resolve(req);
} catch (err) {
reject(err);
}
});
});
};
81 changes: 81 additions & 0 deletions lab-ron/lib/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// node dependencies
const http = require('http');
const requestParser = require('./request-parser.js');
const cowsay = require('cowsay');

const app = http.createServer((req, res) => {

requestParser(req)
.then(req => {
if (req.method === 'GET' && req.url.pathname === '/') {
res.writeHead(200, {
'Content-Type': 'text/html',
});
res.write(`
<!DOCTYPE html><html>
<head><title>Welcome To Cowsay</title></head><body><header>
<h1>CowSay</h1>
<nav><ul>
<li><a href="/">home</a></li>
<li><a href="/cowsay">cowsay</a></li>
</ul></nav></header><main>
<p>Welcome to cowsay, navigate click on the </p></main></body></html>
`);
res.end();
return;
}
if (req.method === 'GET' &&
req.url.pathname === '/cowsay') {

let message = '';
if (req.url.query.text)
message = req.url.query.text;
else
message = 'I need something to say!!';
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(`
<!DOCTYPE html>
<html>
<head>
<title> cowsay </title>
</head>
<body>
<h1> cowsay </h1>
<p>Make the cow say</p>
<pre>
${cowsay.say({ text: message })}
</pre>
<p>at the end of the URL type <b>/cowsay?text=<i>your message here</i></b></p>
</body>
</html>`);

console.log('req.url.pathname', req.url.query);
res.end();
return;
}
if (req.method === 'POST' && req.url.pathname === '/api/cowsay') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify({ message: cowsay.say(req.body) }));
res.end();
return;
}
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.write(`resource ${req.url.pathname} not found!`);
console.log(res); // testing
res.end();
})
.catch(err => {
console.log(err);
res.writeHead(400, {
'Content-Type': 'text/plain',
});
res.write('bad request');
res.end();
});
});

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