Documentation, adding comments and removing old console.log statemenets

This commit is contained in:
Jacob Windle 2019-01-26 08:14:42 -05:00
parent cb120763e1
commit 9cae2a9bad

View File

@ -3,12 +3,21 @@ var http = require('http');
var fs = require('fs');
var winston = require("winston");
// Rudimentary logger.
// TODO - Make this filename configurable.
const logger = winston.createLogger({
transports: [
new winston.transports.File({filename: 'proxy.log'})
]
});
/**
* HttpRequest class,
*
* Encapsulates logging a request.
*
* TODO - Enable request forwarding here.
*/
class HttpRequest {
constructor(attrs) {
this.attrs = attrs;
@ -16,7 +25,9 @@ class HttpRequest {
this.forwardRequest = this.forwardRequest.bind(this);
}
// TODO - not working yet. will come back to this.
/**
* Using Winston, log the request.
*/
logSomething() {
logger.log({
level: 'info',
@ -24,8 +35,13 @@ class HttpRequest {
})
}
/**
* Forward the request, returning a promise for the result.
*
* TODO - Implement me.
*/
async forwardRequest() {
// TODO - rebuild the request and return it to the client.
}
}
@ -34,15 +50,16 @@ class HttpRequest {
* @param {String} bytes
*/
async function parseHttpRequest(bytes) {
// Object to eventually save in HttpRequest class.
let httpRequestAttrs = {headers: {}};
// Parse request row by row.
bytes.split("\r\n").map((row) => {
// Match against HTTP verbs from the first row.
if (row.match('GET|POST|PUT|PATCH|UPDATE|DELETE')) {
console.log("FIRST ROW");
console.log(row);
let typeInfo = row.split(" ");
// Malformed if there aren't at least 3 items here.
if (typeInfo.length !== 3) {
console.log("Bad HTTP request");
return null;
@ -52,8 +69,8 @@ async function parseHttpRequest(bytes) {
httpRequestAttrs["Path"] = typeInfo[1];
httpRequestAttrs["HttpVersion"] = typeInfo[2];
} else {
// Headers, parse accordingly
let currentRow = row.split(":");
console.log(currentRow);
if (currentRow[0] !== '')
httpRequestAttrs.headers[currentRow[0]] = currentRow[1].trim();
}
@ -62,21 +79,16 @@ async function parseHttpRequest(bytes) {
return new HttpRequest(httpRequestAttrs);
}
/**
* Log the request and forward it.
* @param {String} bytes
*/
async function logAndSend(bytes) {
console.log(bytes)
}
function startServer() {
// Start the server, set up data and end handlers.
var server = net.createServer((socket) => {
socket.on('end', (c) => {
console.log("Client disconnected");
});
socket.on("data", (c) => {
// Parse HTTP Request returns promise for HttpRequest (async).
// Log it and pass that along.
parseHttpRequest(c.toString())
.then((req) => {
req.logSomething();
@ -88,10 +100,12 @@ function startServer() {
});
})
// Connection handler (currently unused).
server.on('connection', (c) => {
console.log("Client connected!");
});
// Start the server
server.listen(8124, () => {
console.log("Server bound.");
});