Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

My comments on all of the code #82

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,4 +1 @@
{
"editor.fontSize": 42,
"terminal.integrated.fontSize": 60
}
{}
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

152 changes: 90 additions & 62 deletions public/js/main.js
Original file line number Diff line number Diff line change
@@ -1,69 +1,97 @@
const deleteBtn = document.querySelectorAll('.del')
const todoItem = document.querySelectorAll('.todoItem span')
const todoComplete = document.querySelectorAll('.todoItem span.completed')
// Get array of buttons that have a class of .del
const deleteBtn = document.querySelectorAll(".del");
// Gets array of span tags that is nested under each todoItem class
const todoItem = document.querySelectorAll(".todoItem span");
// Get array of span items with a class of completed nested under the todoItem class
const todoComplete = document.querySelectorAll(".todoItem span.completed");

Array.from(deleteBtn).forEach((el)=>{
el.addEventListener('click', deleteTodo)
})
// Convert deleteBtn to an array and then execute a loop for each item in the array
Array.from(deleteBtn).forEach((el) => {
// If delete button is clicked, execute the deleteTodo
el.addEventListener("click", deleteTodo);
});

Array.from(todoItem).forEach((el)=>{
el.addEventListener('click', markComplete)
})
// Convert todoItem to an array and then execute a loop for each item in the array
Array.from(todoItem).forEach((el) => {
// If toodoItem is clicked, execute the markComplete
el.addEventListener("click", markComplete);
});

Array.from(todoComplete).forEach((el)=>{
el.addEventListener('click', undo)
})
// Convert todoComplete to an array and then execute a loop for each item in the array
Array.from(todoComplete).forEach((el) => {
// If toodoComplete is clicked, execute undo
el.addEventListener("click", undo);
});

async function deleteTodo(){
const todoText = this.parentNode.childNodes[1].innerText
try{
const response = await fetch('deleteTodo', {
method: 'delete',
headers: {'Content-type': 'application/json'},
body: JSON.stringify({
'rainbowUnicorn': todoText
})
})
const data = await response.json()
console.log(data)
location.reload()
}catch(err){
console.log(err)
}
async function deleteTodo() {
// Gets the inner text of the todoItem
const todoText = this.parentNode.childNodes[1].innerText;
try {
// Sends a delete request to the deleteTodo route with a header of appplication/json, and a rainbowUnicorn property set to the todoText
const response = await fetch("deleteTodo", {
method: "delete",
headers: { "Content-type": "application/json" },
body: JSON.stringify({
rainbowUnicorn: todoText,
}),
});
// Takes the response object and gets the json object back that was passed to it in the app.delete
const data = await response.json();
// Output in browser console the json message
console.log(data);
// Reloads the webpage
location.reload();
} catch (err) {
// Catches errors
console.log(err);
}
}

async function markComplete(){
const todoText = this.parentNode.childNodes[1].innerText
try{
const response = await fetch('markComplete', {
method: 'put',
headers: {'Content-type': 'application/json'},
body: JSON.stringify({
'rainbowUnicorn': todoText
})
})
const data = await response.json()
console.log(data)
location.reload()
}catch(err){
console.log(err)
}
// For each todo item that does not have a span of completed, execute this function, if clicked.
async function markComplete() {
// Get inner text of todo item
const todoText = this.parentNode.childNodes[1].innerText;
try {
// send a fetch request with a put method, and pass the todoText value to it
const response = await fetch("markComplete", {
method: "put",
headers: { "Content-type": "application/json" },
body: JSON.stringify({
rainbowUnicorn: todoText,
}),
});
// Wait for the response to resolve and then parses the JSON into a javascript object
const data = await response.json();
// Console log the response
console.log(data);
// reload and execute the get request
location.reload();
} catch (err) {
// Catches any errors
console.log(err);
}
}

async function undo(){
const todoText = this.parentNode.childNodes[1].innerText
try{
const response = await fetch('undo', {
method: 'put',
headers: {'Content-type': 'application/json'},
body: JSON.stringify({
'rainbowUnicorn': todoText
})
})
const data = await response.json()
console.log(data)
location.reload()
}catch(err){
console.log(err)
}
}
// This function is executed when items that have the class of completed are clicked, and so what this function does is it undoes the complete
async function undo() {
// Gets the inner text of the list item
const todoText = this.parentNode.childNodes[1].innerText;
try {
// Sends a fetch PUT request to the server and passes in a object of todoText which contains the text of the list item
const response = await fetch("undo", {
method: "put",
headers: { "Content-type": "application/json" },
body: JSON.stringify({
rainbowUnicorn: todoText,
}),
});
// Waits to get back the json response sent by the server, and turns it into a JSON object
const data = await response.json();
// Outputs the response sent by the server
console.log(data);
// Reload the page by sending a get request
location.reload();
} catch (err) {
// Catches all errors
console.log(err);
}
}
174 changes: 112 additions & 62 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,74 +1,124 @@
const express = require('express')
const app = express()
const MongoClient = require('mongodb').MongoClient
const PORT = 2121
require('dotenv').config()
// import express
const express = require("express");
// Use express constructor function to initialize an express object??
const app = express();
// import and use the MongoClient Client
const MongoClient = require("mongodb").MongoClient;
// sets the port to be 2121
const PORT = 2121;
// Can now use environment config files with a .env extension
require("dotenv").config();

// initializing db, connectionString and dbName variables
let db,
dbConnectionStr = process.env.DB_STRING,
dbName = 'todo'
dbConnectionStr = process.env.DB_STRING,
dbName = "todo";

MongoClient.connect(dbConnectionStr, {useUnifiedTopology: true})
.then(client => {
console.log(`Hey, connected to ${dbName} database`)
db = client.db(dbName)
})
.catch(err =>{
console.log(err)
})
// Connect to the database with our MongoClient.connect method, passing in our connection string and a few options
MongoClient.connect(dbConnectionStr, { useUnifiedTopology: true })
.then((client) => {
// Outputs the fact that database has connected once the connect method resolves
console.log(`Hey, connected to ${dbName} database`);
// Once we have logged in, we select the database we want to connect
db = client.db(dbName);
})
.catch((err) => {
// If there is an error, log it
console.log(err);
});

app.set('view engine', 'ejs')
app.use(express.static('public'))
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
// Use ejs to render our templates
app.set("view engine", "ejs");
// Middleware section here
// Public states that anything in the public folder can be readily called
app.use(express.static("public"));
// I believe this helps parse the body portion of requests
app.use(express.urlencoded({ extended: true }));
// Converts json to JavaScript objects
app.use(express.json());

app.get('/', async (req,res)=>{
const todoItems = await db.collection('todos').find().toArray()
const itemsLeft = await db.collection('todos').countDocuments({completed: false})
res.render('index.ejs', {zebra: todoItems, left: itemsLeft})
})
// client login > database > collection > documents (rows)
// Handle a get request
app.get("/", async (req, res) => {
// Gets and waits for the full list of documents from our collection
const todoItems = await db.collection("todos").find().toArray();
// Counts the number of documents that have the completed property set to false
const itemsLeft = await db
.collection("todos")
.countDocuments({ completed: false });
// renders the ejs file, while setting the zebra property to todoItems, and left to itemsLeft
res.render("index.ejs", { zebra: todoItems, left: itemsLeft });
});

app.post('/createTodo', (req, res)=>{
db.collection('todos').insertOne({todo: req.body.todoItem, completed: false})
.then(result =>{
console.log('Todo has been added!')
res.redirect('/')
})
})
// Executed when a post request to the /createTodo path is created
app.post("/createTodo", (req, res) => {
// access the todos collection and insert this post item
db.collection("todos")
.insertOne({ todo: req.body.todoItem, completed: false })
.then((result) => {
// Once we have inserted and the above method resolves, log todo has been added
console.log("Todo has been added!");
// Send a get request to /
res.redirect("/");
});
});

app.put('/markComplete', (req, res)=>{
db.collection('todos').updateOne({todo: req.body.rainbowUnicorn},{
// Modify an existing item and mark an item as being complete. Only gets executed if the todo item does not have a class of complete
app.put("/markComplete", (req, res) => {
// In the todos collection, find the item with that specific text and "set" completed to true
db.collection("todos")
.updateOne(
{ todo: req.body.rainbowUnicorn },
{
$set: {
completed: true
}
})
.then(result =>{
console.log('Marked Complete')
res.json('Marked Complete')
})
})
completed: true,
},
}
)
// Once the above code resolves, on the server end, out put Market completed
.then((result) => {
console.log("Marked Complete");
// To the browser send a json response of Marked Complete
res.json("Marked Complete");
});
});

app.put('/undo', (req, res)=>{
db.collection('todos').updateOne({todo: req.body.rainbowUnicorn},{
// Modify an existing to do item, but this only gets executed on todo items with a class of completed
app.put("/undo", (req, res) => {
db.collection("todos")
// Find the todo item with the matching text, and "set" completed property to false
.updateOne(
{ todo: req.body.rainbowUnicorn },
{
$set: {
completed: false
}
})
.then(result =>{
console.log('Marked Complete')
res.json('Marked Complete')
completed: false,
},
}
)
// Once above code resolves, output on the server "Marked Complete"
.then((result) => {
console.log("Marked Complete");
// Send a JSON response stating Marked Complete
res.json("Marked Complete");
});
});
// executes when there is a delete request on the /deleteTodo route
app.delete("/deleteTodo", (req, res) => {
// In the todos collection, delete the first Item that has todo of rainbowUnicorn property
db.collection("todos")
.deleteOne({ todo: req.body.rainbowUnicorn })
.then((result) => {
// If success, send a message saying that the todo was deleted.
console.log("Deleted Todo");
// Send a json response back. Converts the string "Deleted It" into JSON
res.json("Deleted It");
})
})
// Catches any errors
.catch((err) => console.log(err));
});

app.delete('/deleteTodo', (req, res)=>{
db.collection('todos').deleteOne({todo:req.body.rainbowUnicorn})
.then(result =>{
console.log('Deleted Todo')
res.json('Deleted It')
})
.catch( err => console.log(err))
})

app.listen(process.env.PORT || PORT, ()=>{
console.log('Server is running, you better catch it!')
})
// Listens on the port of the environment port first. If there is no environment port, then use the PORT defined in this document which is 2121
app.listen(process.env.PORT || PORT, () => {
// Output the below message indicating that the app is listening for a command
console.log("Server is running, you better catch it!");
});
Loading