From d180267434672b4beaa5cc8772a105a1e291e26a Mon Sep 17 00:00:00 2001
From: abbasf <Famboupe.Abbas@Student.Reutlingen-University.DE>
Date: Fri, 21 Mar 2025 20:23:06 +0100
Subject: [PATCH] finished logic for the database interactions

---
 src/Controller.js         | 111 ++++++++++++++++++++++++++++++++++++++
 src/DatabaseController.js |  55 +++++++++++++++++++
 2 files changed, 166 insertions(+)
 create mode 100644 src/DatabaseController.js

diff --git a/src/Controller.js b/src/Controller.js
index e69de29..c21ce84 100644
--- a/src/Controller.js
+++ b/src/Controller.js
@@ -0,0 +1,111 @@
+const todoForm = document.querySelector('form');
+const todoInput = document.getElementById('txt-todo');
+const todoList = document.getElementById('list-todo');
+
+const url = "http://localhost:5000/todos";
+let todoElements = [];
+
+// Method used to put the data in the list of elements
+async function fetchTodoElements(){
+    const response = await fetch(url);
+    todoElements = await response.json();
+    updateList();
+}
+
+fetchTodoElements();
+
+//Used by the button next to the textbox
+todoForm.addEventListener('Submit', function(e){
+    e.preventDefault();
+    addTodoElement();
+})
+
+//Method updates the list in the HTML doc
+async function updateList(){
+    todoList.innerHTML = "";
+    todoElements.forEach(()=>{
+        const todoElement = createItem(todo, index);
+        todoList.append(todoElement);
+    })
+}
+
+//Method to add a new element
+async function addTodoElement(){
+    const todoTxt = todoInput.value.trim();
+    if(todoTxt.length > 0){
+        const response = await fetch(url, {
+            method: "POST",
+            headers: {"Content-Type": "application/json"},
+            body: JSON.stringify({text: todoTxt}),
+        });
+
+        const addedTodo = await response.json();
+        todoElements.push();
+        updateList();
+        todoInput.value = "";
+    }
+}
+
+//Method to update the status of an element
+async function updateStatus(index, isChecked){
+    const todoId = todoElements[index]._id;
+    let newStatus;
+    if(isChecked){
+        newStatus = "closed";
+    }else{
+        newStatus = "open";
+    }
+
+    await fetch(`${url}$/${todoId}`, {
+        method: "PATCH",
+        headers: {"Content-Type": "application/json"},
+        body: JSON.stringify({status: newStatus}),
+    });
+
+    todoElements[index].status = newStatus;
+}
+
+//Method to delete an element from the database
+async function deleteElement(index){
+    const todoId = todoElements[index]._id;
+
+    await fetch(`${url}/${todoId}`, {
+        method: "DELETE",
+    });
+
+    todoElements.splice(index, 1);
+    updateList();
+}
+
+function createItem(todo, index) {
+    const todoListNode = document.createElement("li");
+    const itemId = "item-" + index;
+    todoListNode.className = "items-todo";
+
+    const isChecked = todo.status === "closed";
+
+    todoListNode.innerHTML = `
+        <input type="checkbox" id="${itemId}" ${isChecked ? "checked" : ""}>
+        <label class="custom-checkbox" for="${itemId}"></label>
+        <label for="${itemId}" class="item-text">
+            ${todo.text}
+        </label>
+        <button class="btn-delete">
+            <svg fill="var(--secondary-color)" xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px">
+                <path d="M280-120q-33 0-56.5-23.5T200-200v-520h-40v-80h200v-40h240v40h200v80h-40v520q0 33-23.5 56.5T680-120H280Zm400-600H280v520h400v-520ZM360-280h80v-360h-80v360Zm160 0h80v-360h-80v360ZM280-720v520-520Z"/>
+            </svg>
+        </button>
+    `;
+
+    // Event-Listener für das Löschen eines Todos
+    todoListNode.querySelector(".btn-delete").addEventListener("click", function() {
+        deleteElement(index);
+    });
+
+    // Event-Listener für das Ändern des Status
+    todoListNode.querySelector(`#${itemId}`).addEventListener("change", function(event) {
+        updateStatus(index, event.target.checked);
+    });
+
+    return todoListNode;
+}
diff --git a/src/DatabaseController.js b/src/DatabaseController.js
new file mode 100644
index 0000000..ed8653a
--- /dev/null
+++ b/src/DatabaseController.js
@@ -0,0 +1,55 @@
+const express = require("express");
+const mongoose = require("mongoose");
+const cors = require("cors");
+
+const app = express();
+const PORT = process.env.PORT || 5000;
+
+app.use(cors());
+app.use(express.json());
+
+const uri = "mongodb+srv://famboupeabbas:dbCloudComputing@todocloudcomputing.pcms2.mongodb.net/?retryWrites=true&w=majority&appName=todoCloudComputing";
+
+//Method to create database connection
+mongoose.connect(uri)
+    .then(() => console.log('Connection established :)'))
+    .catch(err => {
+        console.error('Failed to setup the connection to the database', err.message);
+        process.exit(1);});
+
+const Template = new mongoose.Schema({
+    task: String,
+    status: {type: string, default: "open"}
+});
+
+const todoTemplate = mongoose.model("Todo", Template);
+
+app.listen(PORT, () => console.log(`Server was started on port  ${PORT}`));
+
+//Method to fetch all the elements from the database
+app.get("/todos", async (req, res) => {
+    const fetchesTodos = await todoTemplate.find();
+    res.json(fetchesTodos);
+});
+
+//Method to add an element to the database
+app.post("/todos", async (req, res) => {
+    const addedTodo = new Template({text: req.body.text, status: "open"});
+    await addedTodo.save();
+    res.json(addedTodo);
+});
+
+//Method to update an element within the database
+app.patch("/todos/:id", async (req, res) => {
+   const todo = await todoTemplate.findByIdAndUpdate(req.params.id, {status: req.body.status}, {new: true});
+   res.json(todo);
+});
+
+//Method to delete an element from the database
+app.delete("/todos/:id", async(req, res) => {
+   await todoTemplate.findByIdAndDelete(req.params.id);
+   res.json({message: "Element was deleted"});
+});
+
+
+
-- 
GitLab