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

Commented each line. #62

Open
wants to merge 3 commits 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
4 changes: 0 additions & 4 deletions .vscode/settings.json

This file was deleted.

Binary file added 16599529192.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
96 changes: 48 additions & 48 deletions public/js/main.js
Original file line number Diff line number Diff line change
@@ -1,69 +1,69 @@
const deleteBtn = document.querySelectorAll('.del')
const todoItem = document.querySelectorAll('.todoItem span')
const todoComplete = document.querySelectorAll('.todoItem span.completed')
const deleteBtn = document.querySelectorAll('.del') // I don't understand why this is set up this way
const todoItem = document.querySelectorAll('.todoItem span') // I don't understand why this is set up this way
const todoComplete = document.querySelectorAll('.todoItem span.completed') // I don't understand why this is set up this way

Array.from(deleteBtn).forEach((el)=>{
el.addEventListener('click', deleteTodo)
Array.from(deleteBtn).forEach((el)=>{ // takes the array from deleteBtn and puts event listener on each
el.addEventListener('click', deleteTodo) // adds event listener to the button for when it's clicked
})

Array.from(todoItem).forEach((el)=>{
el.addEventListener('click', markComplete)
Array.from(todoItem).forEach((el)=>{ // takes the array from todoItem and puts event listener on each
el.addEventListener("click", markComplete); // adds event listener for when it's clicked
})

Array.from(todoComplete).forEach((el)=>{
el.addEventListener('click', undo)
Array.from(todoComplete).forEach((el)=>{ //takes the array from todoComplete and puts event listener on each
el.addEventListener("click", undo); // adds event listener for when it's clicked
})

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
async function deleteTodo(){ // defines this as an async function
const todoText = this.parentNode.childNodes[1].innerText // defines this as the inner text of the span
try{ // asks to try the code inside it
const response = await fetch('deleteTodo', {// await won't run until the deleteTodo is run
method: 'delete', // tells the server to delete
headers: {'Content-type': 'application/json'}, // tells the server what to expect & specifies the content type as a json application
body: JSON.stringify({ // sends the data to the server as a string as it has to be
'rainbowUnicorn': todoText // sends the span innertext we clicked on to the server as "rainbowUnicorn"
})
})
const data = await response.json()
const data = await response.json() // sets data to await the JSON to be extracted
console.log(data)
location.reload()
}catch(err){
console.log(err)
location.reload()//reload the data, works the smae as refreshing browser
}catch(err){ // if there's an exception catch will take it
console.log(err) // and console log it because we told it to
}
}

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
async function markComplete(){ // defines this as an async function
const todoText = this.parentNode.childNodes[1].innerText // sets todoText as the span we clicked
try{ // tells it to try the code in the curly brackets
const response = await fetch('markComplete', { // awaits the fetch of mark complete
method: 'put', // tells server it's updating something
headers: {'Content-type': 'application/json'}, // tells the server what to expect & specifies the content type as a json application
body: JSON.stringify({ // turns the request into a string
'rainbowUnicorn': todoText // calls the content stored "rainbowUnicorn"
})
})
const data = await response.json()
const data = await response.json() // sets data to extracted JSON
console.log(data)
location.reload()
}catch(err){
location.reload() // refreshes browser
}catch(err){ // catches 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)
}
async function undo(){// defines this as an async function
const todoText = this.parentNode.childNodes[1].innerText; // sets todoText as the span we clicked
try { // trys the code inside curly brces
const response = await fetch("undo", { // defines response as the result of the fetch action
method: "put", // tells server it's updating something
headers: { "Content-type": "application/json" }, // tells server to expect JSON back
body: JSON.stringify({ // turns data into a JSON string
rainbowUnicorn: todoText, // the data we extracted form the span in assinged rainbowUNicorn
}),
});
const data = await response.json(); // sets data to extracted JSON
console.log(data);
location.reload(); // refreshes app
} catch (err) { // catches errors
console.log(err); // console logs the errors
}
}
69 changes: 35 additions & 34 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,74 +1,75 @@
const express = require('express')
const app = express()
const MongoClient = require('mongodb').MongoClient
const PORT = 2121
require('dotenv').config()
const express = require('express') // Requiring express
const app = express() // telling code when we use app to use express methods
const MongoClient = require('mongodb').MongoClient //requireing MongoClient when we use that variable
const PORT = 2121 // setting our port to 2121, telling the code when we use PORT to use that variable.
require('dotenv').config() //requiring dotenv

let db,
dbConnectionStr = process.env.DB_STRING,
dbName = 'todo'
dbConnectionStr = process.env.DB_STRING, // telling code where to get the connection string for the DB when we use dbConnectionStr
dbName = 'todo' // telling our server what to use when it sees dbName

MongoClient.connect(dbConnectionStr, {useUnifiedTopology: true})
MongoClient.connect(dbConnectionStr, {useUnifiedTopology: true}) // connecting to MongoDB using the previously defined connection string
.then(client => {
console.log(`Hey, connected to ${dbName} database`)
db = client.db(dbName)
console.log(`Hey, connected to ${dbName} database`) // Visual cue that we've connected to the database
db = client.db(dbName) // telling the server to redefine db to the database it finds with the name we defined earlier.
})
.catch(err =>{
console.log(err)
console.log(err) // console logging any error we throw up in the connection.
})

app.set('view engine', 'ejs')
app.use(express.static('public'))
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
// Middleware
app.set('view engine', 'ejs') // telling our server to render .ejs files
app.use(express.static('public')) // telling express to pul our static files from 'public' folder
app.use(express.urlencoded({ extended: true })) // parses URLEncoded requests
app.use(express.json()) // parses incoming JSON files

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})
const todoItems = await db.collection('todos').find().toArray() // finding the database entries and putting them into an array
const itemsLeft = await db.collection('todos').countDocuments({completed: false}) // counts documents that are marked as false
res.render('index.ejs', {zebra: todoItems, left: itemsLeft}) //renders these in the index.ejs file
})

app.post('/createTodo', (req, res)=>{
db.collection('todos').insertOne({todo: req.body.todoItem, completed: false})
db.collection('todos').insertOne({todo: req.body.todoItem, completed: false}) //adds the user's input to the database, auto marking complete to false
.then(result =>{
console.log('Todo has been added!')
res.redirect('/')
res.redirect('/') // reloads the page
})
})

app.put('/markComplete', (req, res)=>{
db.collection('todos').updateOne({todo: req.body.rainbowUnicorn},{
app.put('/markComplete', (req, res)=>{ // creates path for API to update the complete field
db.collection('todos').updateOne({todo: req.body.rainbowUnicorn},{ // searches for the clicked task
$set: {
completed: true
completed: true // updates the complete to "true"
}
})
.then(result =>{
console.log('Marked Complete')
res.json('Marked Complete')
res.json('Marked Complete') // sends the result to main.js as JSON
})
})

app.put('/undo', (req, res)=>{
db.collection('todos').updateOne({todo: req.body.rainbowUnicorn},{
app.put('/undo', (req, res)=>{ // sets path to undo complete on click
db.collection('todos').updateOne({todo: req.body.rainbowUnicorn},{ // searches for the clicked task in the database
$set: {
completed: false
completed: false // sets complete to false
}
})
.then(result =>{
console.log('Marked Complete')
res.json('Marked Complete')
res.json('Marked Complete') // sends response to main.js as JSON
})
})

app.delete('/deleteTodo', (req, res)=>{
db.collection('todos').deleteOne({todo:req.body.rainbowUnicorn})
app.delete('/deleteTodo', (req, res)=>{ // sets path for deleting a task
db.collection('todos').deleteOne({todo:req.body.rainbowUnicorn}) // searches for the task in the database
.then(result =>{
console.log('Deleted Todo')
res.json('Deleted It')
res.json('Deleted It') // sends the delete to the main.js as JSON
})
.catch( err => console.log(err))
.catch( err => console.log(err)) // catches any errors
})

app.listen(process.env.PORT || PORT, ()=>{
console.log('Server is running, you better catch it!')
app.listen(process.env.PORT || PORT, ()=>{ // makes the server listen for requests on the port specified by Heroku or the default port set earlier
console.log('Server is running, you better catch it!') // visual cue that the server is running successfully.
})
18 changes: 9 additions & 9 deletions views/index.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,23 @@
<body>
<h1>Todos</h1>
<ul>
<% for(let i = 0; i < zebra.length; i++) { %>
<% for(let i = 0; i < zebra.length; i++) { %> <!-- Looping through the array returned from the database -->
<li class='todoItem'>
<% if(zebra[i].completed === true) {%>
<span class="completed"><%= zebra[i].todo %></span>
<% if(zebra[i].completed === true) {%> <!-- checking if the completed property is true -->
<span class="completed"><%= zebra[i].todo %></span> <!--if it's true give it class completed and put the info into the ul as li-->
<% }else{ %>
<span><%= zebra[i].todo %></span>
<span><%= zebra[i].todo %></span> <!-- If it's not just put the info into the ul as li-->
<% } %>
<span class='del'> Delete </span>
<span class='del'> Delete </span> <!-- add the delete span so we can delete content later -->
</li>
<% } %>
</ul>

<h2>Things left to do: <%= left %></h2>
<h2>Things left to do: <%= left %></h2> <!-- keeps a count of things that aren't marked as completed = true -->

<form action="/createTodo" method='POST'>
<input type="text" placeholder="Enter Todo Item" name='todoItem'>
<input type="submit">
<form action="/createTodo" method='POST'> <!-- defines action to call from server and tells the server it's making a post request-->
<input type="text" placeholder="Enter Todo Item" name='todoItem'> <!--the input for text-->
<input type="submit"> <!--the submit button-->
</form>

<script src="js/main.js"></script>
Expand Down