Skip to content

Instantly share code, notes, and snippets.

@khannedy
Created December 26, 2021 02:23
Show Gist options
  • Save khannedy/63f7b449e06b5a3a9d98ebf95a4fd35a to your computer and use it in GitHub Desktop.
Save khannedy/63f7b449e06b5a3a9d98ebf95a4fd35a to your computer and use it in GitHub Desktop.
Simple Todolist API using NodeJS Native
import http from "http";
class TodoListService {
todolist = ["Eko", "Kurniawan", "Khannedy"];
getTodoListAsObject() {
const result = [];
for (let i = 0; i < this.todolist.length; i++) {
result.push({
id: i, todo: this.todolist[i]
})
}
return result;
}
async getTodolist(request, response) {
console.info("Get todolist");
response.write(JSON.stringify({
code: 200, status: "OK", data: this.getTodoListAsObject()
}))
response.end();
}
async addTodolist(request, response) {
console.info("Add todolist");
request.addListener("data", async (data) => {
console.info(`Receive add todolist with body : ${data.toString()}`);
const body = JSON.parse(data.toString());
this.todolist.push(body.todo);
response.write(JSON.stringify({
code: 200, status: "OK", data: this.getTodoListAsObject()
}))
response.end();
})
}
async updateTodolist(request, response) {
console.info("Update todolist");
request.addListener("data", async (data) => {
console.info(`Receive update todolist with body : ${data.toString()}`);
const body = JSON.parse(data.toString());
if (this.todolist[body.id]) {
this.todolist[body.id] = body.todo;
}
response.write(JSON.stringify({
code: 200, status: "OK", data: this.getTodoListAsObject()
}))
response.end();
})
}
async removeTodolist(request, response) {
console.info("Remove todolist");
request.addListener("data", async (data) => {
console.info(`Receive remove todolist with body : ${data.toString()}`);
const body = JSON.parse(data.toString());
this.todolist.splice(body.id, 1);
response.write(JSON.stringify({
code: 200, status: "OK", data: this.getTodoListAsObject()
}))
response.end();
})
}
}
const todoListService = new TodoListService();
const server = http.createServer(async (request, response) => {
response.setHeader('Content-Type', 'application/json');
if (request.method === "GET") {
await todoListService.getTodolist(request, response);
} else if (request.method === "POST") {
await todoListService.addTodolist(request, response);
} else if (request.method === "DELETE") {
await todoListService.removeTodolist(request, response);
} else if (request.method === "PUT") {
await todoListService.updateTodolist(request, response);
}
});
server.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment