Skip to content

Commit

Permalink
feat: added helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
mzeiher committed Nov 4, 2024
1 parent 5fd2b70 commit ad9dae2
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 23 deletions.
46 changes: 46 additions & 0 deletions exercises/javascript/todo-app/spa/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const wsServer = new WebSocketServer({ noServer: true });

const wsClients = new Set();

// logic goes here
const server = createServer((req, res) => {
if (
req.method === "GET" &&
Expand All @@ -18,9 +19,17 @@ const server = createServer((req, res) => {
res.setHeader("content-type", "application/javascript");
res.statusCode = 200;
res.end(readFileSync("./client.js", { encoding: "utf8" }));
} else if (req.method === "POST" && req.url === "/add") {
res.statusCode = 501;
res.end("not implemented");
} else if (req.method === "DELETE") {
res.statusCode = 501;
res.end("not implemented");
}
});

// websocket logic all connected clients are stored in the set `wsClients`
// no need to expand
server.on("upgrade", (req, socket, head) => {
wsServer.handleUpgrade(req, socket, head, (client) => {
client.on("open", () => {
Expand All @@ -42,3 +51,40 @@ server.on("upgrade", (req, socket, head) => {
server.listen(3000, () => {
console.log("listening on :3000");
});

// some helpers to parse the query part from a URL or parse the body from a request

/**
* @param url {string}
* @returns { Promise<{[name:string]:string}> }
*/
function parseQuery(url) {
const query = url.split("?")[1] ?? "";
const result = query.split("&").reduce((prev, curr) => {
const keyValue = curr.split("=");
prev[keyValue[0]] = keyValue[1];
return prev;
}, {});
return result;
}

/**
* @param req { IncomingMessage }
* @returns { Promise<{[name:string]:string}> }
*/
function parseBody(req) {
return new Promise((resolve) => {
let buffer = "";
req.on("data", (chunk) => {
buffer += chunk;
});
req.on("end", () => {
const result = buffer.split("\n").reduce((prev, curr) => {
const keyValue = curr.split("=");
prev[keyValue[0]] = keyValue[1];
return prev;
}, {});
resolve(result);
});
});
}
77 changes: 54 additions & 23 deletions exercises/javascript/todo-app/ssr/server.js
Original file line number Diff line number Diff line change
@@ -1,48 +1,79 @@
import { createServer } from "node:http";
import { createServer, IncomingMessage } from "node:http";

let todos = [];

const server = createServer((req, res) => {
// handle get request
if (req.method === "GET") {
res.setHeader("Content-Type", "text/html");
res.statusCode = 200;
res.end(renderPage());
} else if (req.method === "POST") {
let body = "";
req.on("data", chunk => {
body += chunk.toString();
});
req.on("end", () => {
// implement adding of todo or deleting
res.statusCode = 501;
res.end("not implemented");
});
}
// handle get request
if (req.method === "GET") {
res.setHeader("Content-Type", "text/html");
res.statusCode = 200;
res.end(renderPage());
} else if (req.method === "POST" && req.url === "/add") {
parseBody(req).then((params) => {
res.statusCode = 501;
res.end("not implemented");
});
}
});

function renderPage() {
return `<!doctype html>
return `<!doctype html>
<html>
<head>
<title>Todo App</title>
<meta charset="utf-8">
</heade>
<body>
<h1>Todo App</h1>
<form method="POST" action="/">
<form method="POST" action="/add">
<input type="text" name="todo" placeholder="Enter a new todo">
<button type="submit">Add</button>
</form>
<ul>
${todos.map(todo => `<li>${todo}</li>`).join("")}
${todos.map((todo) => `<li>${todo}</li>`).join("")}
</ul>
</body>
</html>
`

`;
}

server.listen(3000, () => {
console.log("Server is running on http://localhost:3000");
console.log("Server is running on http://localhost:3000");
});

// some helpers to parse the query part from a URL or parse the body from a request

/**
* @param url {string}
* @returns { Promise<{[name:string]:string}> }
*/
function parseQuery(url) {
const query = url.split("?")[1] ?? "";
const result = query.split("&").reduce((prev, curr) => {
const keyValue = curr.split("=");
prev[keyValue[0]] = keyValue[1];
return prev;
}, {});
return result;
}

/**
* @param req { IncomingMessage }
* @returns { Promise<{[name:string]:string}> }
*/
function parseBody(req) {
return new Promise((resolve) => {
let buffer = "";
req.on("data", (chunk) => {
buffer += chunk;
});
req.on("end", () => {
const result = buffer.split("\n").reduce((prev, curr) => {
const keyValue = curr.split("=");
prev[keyValue[0]] = keyValue[1];
return prev;
}, {});
resolve(result);
});
});
}

0 comments on commit ad9dae2

Please sign in to comment.