Skip to content

Instantly share code, notes, and snippets.

@anshulrgoyal
Created December 19, 2018 16:25
Show Gist options
  • Select an option

  • Save anshulrgoyal/aa50923c171b4c84ebe0a6a5e841a460 to your computer and use it in GitHub Desktop.

Select an option

Save anshulrgoyal/aa50923c171b4c84ebe0a6a5e841a460 to your computer and use it in GitHub Desktop.
Server Example
"use strict";
//Imports
const http = require("http");
const url = require("url");
const queryString = require("querystring");
const StringDecoder = require("string_decoder").StringDecoder;
// ports for the process
const httpPort = 4443;
// http server
const serverHttp = http.createServer((req, res) => {
serverLogic(req, res);
});
let countNumber = 0;
serverHttp.listen(httpPort, () => {
console.log("http server started in at port " + httpPort);
});
const handler = {
count: (data, cb) => {
const {
method
} = data;
const allowedMethods = ["post", "get"];
if (allowedMethods.indexOf(method) !== -1) {
handler._count[method](data, cb);
} else {
cb(
405, {
err: "unknown method"
},
"json"
);
}
},
_count: {
post: (data, cb) => {
const {
payload: {
value
}
} = data;
countNumber = value;
cb(200, {
sucess: true
}, "json");
},
get: (data, cb) => {
cb(200, {
value: countNumber
}, "json");
}
}
};
const handleNotFound = (data, cb) => {
cb(404, {});
};
const serverLogic = (req, res) => {
//getting the url from the request and parseing it with url.parser and querystring
const parserdUrl = url.parse(req.url, true);
// removing front and end slash from the url
const trimedUrl = parserdUrl.pathname.replace(/^\/|\/$/g, "");
//getting headers and method from req
let {
headers,
method
} = req;
// turning the method to lowercase
method = method.toLowerCase();
// getting query
let queryParameter = parserdUrl.query;
// getting the data from the req
let buffer = "";
// decoding the buffer to string
const decoder = new StringDecoder("utf-8");
req.on("data", function(data) {
buffer += decoder.write(data);
});
req.on("end", function() {
buffer += decoder.end();
if (buffer) {
if (headers["content-type"] === "application/x-www-form-urlencoded")
buffer = queryString.parse(buffer);
if (headers["content-type"] === "application/json")
buffer = JSON.parse(buffer);
}
const chooseHandler =
trimedUrl in handler ? handler[trimedUrl] : handleNotFound;
const data = {
payload: buffer,
queryParameter,
method,
headers,
parserdUrl,
trimedUrl
};
try {
// selecting a handler
chooseHandler(data, (statusCode, payload, contentType) => {
processHandler(res, statusCode, payload, contentType);
});
} catch (e) {
console.log(e);
whenError(res);
}
});
};
const whenError = res => {
res.writeHead(500);
res.end("error");
};
const processHandler = (res, statusCode, payload, contentType) => {
// setting up content type header for response
if ((contentType = "json")) {
payload = JSON.stringify(payload);
res.setHeader("Content-Type", "application/json");
}
res.writeHead(statusCode);
res.end(payload);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment