Skip to content

Instantly share code, notes, and snippets.

@xtpor
Created October 28, 2018 04:23
Show Gist options
  • Save xtpor/48f8b129cd84e6aadd355d9080cdd8c5 to your computer and use it in GitHub Desktop.
Save xtpor/48f8b129cd84e6aadd355d9080cdd8c5 to your computer and use it in GitHub Desktop.
var http = require('http');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var mongourl = 'mongodb://developer:developer123@ds131963.mlab.com:31963/fyp2018';
var server = http.createServer(async function (req, res) {
console.log(`INCOMING REQUEST: ${req.method} ${req.url}`);
const parsedURL = url.parse(req.url, true);
const queryAsObject = parsedURL.query;
const handler = (function () {
switch(parsedURL.pathname) {
case '/displayPeople':
return handlerPrintAllPeople
case '/info':
return handlerPrintUserInfo
default:
return handlerNotFound
}
})()
let db
try {
db = await MongoClient.connect(mongourl)
const result = await handler(db, parsedURL.query)
const contentType = result.contentType || "text/html"
const status = result.status || 200
const response = result.response || ""
res.writeHead(status, contentType)
res.end(response)
} catch (e) {
console.error(e)
res.writeHead(500, {"Content-Type": "text/plain"})
res.write("500 Server Internal Error" + "\n");
res.write(e.message + "\n")
res.write(e.stack + "\n")
res.end()
} finally {
db.close()
}
})
async function handlerPrintAllPeople(db){
const people = await db.collection("fyp2018").find().toArray()
if (people.length == 0) {
return {status: 404, response: `
<html>
<body>
Records Not found!
</body>
</html>
`}
} else {
let response = ""
response += '<html><head><title>fyp2018</title></head>'
response += '<body><H1>fyp2018</H1>'
response += '<h2>Showing ' + people.length + ' documents </h2>'
response += '<ol>'
for (const person of people) {
response += '<li><a href=/info?userid=' + person._id +'>' + person.username + '</a></li>'
}
response += '</ol>'
response += '</body></html>'
return {response}
}
}
async function handlerPrintUserInfo(db, {userid: id}) {
const data = await db.collection("fyp2018").findOne({_id: ObjectId(id)})
if (data === null) {
return {status: 404, response: `
<html>
<head>
<title>Display User Information</title>
</head>
<body>
User not found
</body>
</html>
`}
} else {
return {response: `
<html>
<head>
<title>Display User Information</title>
</head>
<body>
<h1>Display User Information</h1>
<h2>Showing ${data.username} information</h2>
<p>Username: ${data.username}</p>
<p>Sex: ${data.sex}</p>
<p>Email: ${data.email}</p>
</body>
</html>
`}
}
}
async function handlerNotFound() {
return {status: 404, response: "404 NOT FOUND", contentType: "text/plain"}
}
server.listen(process.env.PORT || 8099);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment