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
119 changes: 5 additions & 114 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,124 +1,15 @@
![cf](https://i.imgur.com/7v5ASc8.png) Lab 07: Vanilla HTTP Server
======

## Submission Instructions
* Work in a fork of this repository
* Work in a branch on your fork
* Write all of your code in a directory named `lab-` + `<your name>` **e.g.** `lab-susan`
* Open a pull request to this repository
* Submit on canvas a question and observation, how long you spent, and a link to your pull request
## Read ME
* request-parser.js requires URL and querystring so it can parse and buffer the sting sent over; catching an error if there is on.
* server.js contains the HTML to input the cowsay text pictures and text. It also houses http.createServer which allows the server to show.
* index.js starts the server on PORT 4000 as specified in the env file. It is also the main page for "start" and "watch" in package.json/scripts.
* On the address bar, you can write "http://localhost:4000/?text=hello!" to have the cow say hello! If you would like something else, for instance a dragont to say hello, simply put "http://localhost:4000/?text=hello!&f=dragon" and you got it.

## Resources
* [Cowsay docs](https://github.com/piuccio/cowsay)

## Configuration
Configure the root of your repository with the following files and directories. Thoughfully name and organize any aditional configuration or module files.
* **README.md** - contains documentation
* **.env** - contains env variables **(should be git ignored)**
* **.gitignore** - contains a [robust](http://gitignore.io) `.gitignore` file
* **.eslintrc** - contains the course linter configuratoin
* **.eslintignore** - contains the course linter ignore configuration
* **package.json** - contains npm package config
* create a `lint` script for running eslint
* create a `test` script for running tests
* create a `start` script for running your server
* **lib/** - contains module definitions
* **\_\_test\_\_/** - contains unit tests

## Feature Tasks
For this assignment you will be building a HTTP server.
#### Request Parser
The request parser module should return a promise that parses the request url, querystring, and POST or PUT body (as JSON).

#### Server Module
The server module is responsible for creating an http server defining all route behavior and exporting an interface for starting and stoping the server. It should export an object with `start` and `stop` methods.

###### GET /
When a client makes a GET request to / the server should send baack html with a project description and a anchor to /cowsay.
``` html
<!DOCTYPE html>
<html>
<head>
<title> cowsay </title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="/cowsay">cowsay</a></li>
</ul>
</nav>
<header>
<main>
<!-- project description -->
</main>
</body>
</html>
```

###### GET /cowsay?text={message}
When a client makes a GET request to /cowsay?text={message} the server should parse the querystring for a text key. It should then send a rendered HTML page with a cowsay cow speaking the value of the text query. If their is no text query the cow message should say `'I need something good to say!'`.
``` html
<!DOCTYPE html>
<html>
<head>
<title> cowsay </title>
</head>
<body>
<h1> cowsay </h1>
<pre>
<!-- cowsay.say({text: req.query.text}) -->
</pre>
</body>
</html>
```

###### GET /api/cowsay?text={message}
When a client makes a POST request to /api/cowsay it should send JSON that includes `{"text": "<message>"}`. The server should respond with a JSON body `{"content": "<cowsay cow>"}`.

* A response for a valid Requests should have a status code of 200 and the JSON body
``` json
{
"content": "<cowsay cow text>"
}
```

* A response for a invalid Requests should have a status code of 400 and the JSON body...
```
{
"error": "invalid request: text query required"
}
```
| Request | Response Status Code | Response Type | Response Body |
| -- | -- | -- | -- |
| With out a query | 400 | JSON | `{"error": "invalid request: query required"}` |
| With out text property on the query | 400 | JSON | `{"error": "invalid request: text required"}` |
| With text query | 200 | JSON | `{"content": "<cowsay cow text>"}` |

###### POST /api/cowsay
When a client makes a POST request to /api/cowsay it should send JSON that includes `{"text": "<message>"}`.

* A response for a valid Requests should have a status code of 200 and the JSON body

``` json
{
"content": "<cowsay cow text>"
}
```

* A response for a invalid Requests should have a status code of 400 and the JSON body...
```
{
"error": "invalid request: text query required"
}
```

| Request | Response Status Code | Response Type | Response Body |
| -- | -- | -- | -- |
| With out a body | 400 | JSON | `{"error": "invalid request: body required"}` |
| With out text property on the body | 400 | JSON | `{"error": "invalid request: text required"}` |
| With text body | 200 | JSON | `{"content": "<cowsay cow text>"}` |


## TEST
Write a 200 and 400 test for you POST request to `/api/cowsay`
Expand Down
5 changes: 5 additions & 0 deletions lab-brandon/.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-brandon/.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" ]
}
}
149 changes: 149 additions & 0 deletions lab-brandon/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@

node_modules
.env
# 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

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

const superagent = require('superagent');

describe('POST /api/GET', () => {
test('should respond with 200 response and echo the body', () => {
return superagent.post('http://localhost:4000/api/cowsay')
.send({
text: 'aaaayyy',
})
.then(res => {
expect(res.status).toEqual(200);
expect(res.body).toEqual({'content' : ` ______________________
< aaaayyy >
----------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
`});
});
});

test('should respond with a 400', () => {
return superagent.post('http://localhost:4000/api/coay')
.set({ 'Content-Type': 'application/json'})
.send('{')
.then(Promise.reject)
.catch(res => {
expect(res.status).toEqual(400);
expect(res.res.text).toEqual('bad request');
});
});
});
8 changes: 8 additions & 0 deletions lab-brandon/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
'use strict';

require('dotenv').config();

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

server.start(process.env.PORT, () =>
console.log('server starting on: ', process.env.PORT));
26 changes: 26 additions & 0 deletions lab-brandon/lib/request-parser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'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);
}
});
});
};
Loading