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

Added comments for Class 44 homework #837

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
8 changes: 4 additions & 4 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"editor.fontSize": 42,
"terminal.integrated.fontSize": 62
}
// {
// "editor.fontSize": 42,
// "terminal.integrated.fontSize": 62
// }
124 changes: 62 additions & 62 deletions public/js/main.js
Original file line number Diff line number Diff line change
@@ -1,72 +1,72 @@
const deleteBtn = document.querySelectorAll('.fa-trash')
const item = document.querySelectorAll('.item span')
const itemCompleted = document.querySelectorAll('.item span.completed')
const deleteBtn = document.querySelectorAll('.fa-trash') //setting a variable that grabs the trash can icon
const item = document.querySelectorAll('.item span') //setting a variable that grabs the span with items
const itemCompleted = document.querySelectorAll('.item span.completed') //setting a variable that grabs the selection of spans with a class of 'completed' inside of a parent with a class of 'items'

Array.from(deleteBtn).forEach((element)=>{
element.addEventListener('click', deleteItem)
})
Array.from(deleteBtn).forEach((element) => { //creating an array from our selection and staring a loop
element.addEventListener('click', deleteItem) //adds event listener to the current item that waits for a click and then calls the 'deleteItem' function
}) //close loop

Array.from(item).forEach((element)=>{
element.addEventListener('click', markComplete)
})
Array.from(item).forEach((element) => { //creating an array from our selection and staring a loop
element.addEventListener('click', markComplete) //adds event listener to the current item that waits for a click and then calls the 'markComplete' function
}) //close loop

Array.from(itemCompleted).forEach((element)=>{
element.addEventListener('click', markUnComplete)
})
Array.from(itemCompleted).forEach((element) => { //creating an array from our selection and staring a loop
element.addEventListener('click', markUnComplete) //adds event listener to the current item that waits for a click and then calls the 'markUnComplete' function
}) //close loop

async function deleteItem(){
const itemText = this.parentNode.childNodes[1].innerText
try{
const response = await fetch('deleteItem', {
method: 'delete',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'itemFromJS': itemText
})
})
const data = await response.json()
console.log(data)
location.reload()
async function deleteItem() { //declares an asynchronous function
const itemText = this.parentNode.childNodes[1].innerText //looks inside of the list items and grabs only the inner text within the list span
try { //starting a try block that allows us to do something
const response = await fetch('deleteItem', { //setting a response variable that waits for the retrival of data from the result of the deleteItem route, we are also starting an object
method: 'delete', //sets the CRUD method for the route
headers: { 'Content-Type': 'application/json' }, //specifying teh type of content expected, in this case is json
body: JSON.stringify({ //declare the message content being passed and turn it into a string
'itemFromJS': itemText //itemText is innerText. We're setting the content of the body to the inner text of the item and naming that 'itemFromJS'
}) //closing the body
}) //closing the object
const data = await response.json() //setting a variable called that that waits for the server to respond with some json
console.log(data) //loging the response
location.reload() //refreshes the page to update what is displayed

}catch(err){
console.log(err)
}
}
} catch (err) { //if error occurs pass error into catch block
console.log(err) //log error
}//close catch block
} //end of function

async function markComplete(){
const itemText = this.parentNode.childNodes[1].innerText
try{
const response = await fetch('markComplete', {
method: 'put',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'itemFromJS': itemText
})
})
const data = await response.json()
console.log(data)
location.reload()
async function markComplete() { //declares an asynchronous function
const itemText = this.parentNode.childNodes[1].innerText //looks inside of the list items and grabs only the inner text within the list span
try {//starting a try block that allows us to do something
const response = await fetch('markComplete', { //setting a response variable that waits for the retrival of data from the result of the markComplete route, we are also starting an object
method: 'put', //sets the CRUD method for the route, put means update
headers: { 'Content-Type': 'application/json' }, //specifying teh type of content expected, in this case is json
body: JSON.stringify({ //declare the message content being passed and turn it into a string
'itemFromJS': itemText //We're setting the content of the body to the inner text of the item and naming that 'itemFromJS'
}) //closing body
}) //closing object
const data = await response.json() //setting a variable called that that waits for the server to respond with some json
console.log(data) //loging the response
location.reload() //refreshes the page to update what is displayed

}catch(err){
console.log(err)
}
}
} catch (err) { //if error occurs pass error into catch block
console.log(err) //log error
}//close catch block
}//end of function

async function markUnComplete(){
const itemText = this.parentNode.childNodes[1].innerText
try{
const response = await fetch('markUnComplete', {
method: 'put',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'itemFromJS': itemText
})
})
async function markUnComplete() { //declares an asynchronous function
const itemText = this.parentNode.childNodes[1].innerText //looks inside of the list items and grabs only the inner text within the list span
try { //starting a try block to do something
const response = await fetch('markUnComplete', { //setting a response variable that waits for the retrival of data from the result of the markUnComplete route, we are also starting an object
method: 'put', //sets the CRUD method for the route, put means update
headers: { 'Content-Type': 'application/json' }, //specifying teh type of content expected, in this case is json
body: JSON.stringify({ //declare the message content being passed and turn it into a string
'itemFromJS': itemText //setting the content of the body to the inner text of the item and naming that 'itemFromJS'
}) //closing body
}) //closing object
const data = await response.json()
console.log(data)
location.reload()
console.log(data) //loging the response
location.reload() //refreshes the page to update what is displayed

}catch(err){
console.log(err)
}
}
} catch (err) { //if error occurs pass error into catch block
console.log(err) //log error
}//close catch block
} //end of function
135 changes: 68 additions & 67 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
const express = require('express')
const app = express()
const MongoClient = require('mongodb').MongoClient
const PORT = 2121
require('dotenv').config()
const express = require('express') // making it possible to use express in this file
const app = express() //saving express to the 'app' variable
const MongoClient = require('mongodb').MongoClient //makes it possible to use methods associated with mongoclient and talk to our db
const PORT = 2121 //defining a port and saving it in a constant. It's in all caps bc it's a global const, it's common practice
require('dotenv').config() // allows us to look for variables inside of the .env file


let db,
dbConnectionStr = process.env.DB_STRING,
dbName = 'todo'
let db, //declaring a (global) variable called db but not assigning any value
dbConnectionStr = process.env.DB_STRING, //declaring a variable and assigning our db connection string to it
dbName = 'todo' //declaring a variable and assigning the name of the db we will be using

MongoClient.connect(dbConnectionStr, { useUnifiedTopology: true })
.then(client => {
console.log(`Connected to ${dbName} Database`)
db = client.db(dbName)
})

app.set('view engine', 'ejs')
app.use(express.static('public'))
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
MongoClient.connect(dbConnectionStr, { useUnifiedTopology: true }) //creating a connection to mongodb and passing in our connection string, also passing in an additional property
.then(client => { //the above line establishes a promise, only if the connection is succesfull we want the 'then' to run, we are also passing inn the client information
console.log(`Connected to ${dbName} Database`) //once the connection is succesful a template literal is shown in the console
db = client.db(dbName) //assigning a value to previously declared db variable that contains a db client factory method, this can be used later
}) //closing .then

//all this section of code is midleware, it facilitates communaction for our requests
app.set('view engine', 'ejs') //setting our ejs as a default render method
app.use(express.static('public')) //telling the code to look for static assets in the 'public' folder
app.use(express.urlencoded({ extended: true })) //tells express to decode and encode urls where the header matches the content. Supports arrays and objects
app.use(express.json()) //this code replaces 'bodyParser' it parses json content from incoming requests

app.get('/',async (request, response)=>{
const todoItems = await db.collection('todos').find().toArray()
const itemsLeft = await db.collection('todos').countDocuments({completed: false})
response.render('index.ejs', { items: todoItems, left: itemsLeft })
//express(app) methods
app.get('/', async (request, response) => { //this handles a read request. When its requested it triggers an async function with req and res parameters
const todoItems = await db.collection('todos').find().toArray() //sets a variable and awaits. We are accesing a collection then all the items (find()) from said collection and put them in an array
const itemsLeft = await db.collection('todos').countDocuments({ completed: false }) //sets a variable and awaits a count of uncompleted items to later display in ejs
response.render('index.ejs', { items: todoItems, left: itemsLeft }) //rendering ejs so that it shows an html and we're passing the items and the count remaining inside of an object
// db.collection('todos').find().toArray()
// .then(data => {
// db.collection('todos').countDocuments({completed: false})
Expand All @@ -35,59 +36,59 @@ app.get('/',async (request, response)=>{
// .catch(error => console.error(error))
})

app.post('/addTodo', (request, response) => {
db.collection('todos').insertOne({thing: request.body.todoItem, completed: false})
.then(result => {
console.log('Todo Added')
response.redirect('/')
})
.catch(error => console.error(error))
})
app.post('/addTodo', (request, response) => { //another express method. Starts a POST method when the '/addTodo' route is passed in
db.collection('todos').insertOne({ thing: request.body.todoItem, completed: false }) //look in the db, find the collection 'todos' and inserts a new item into it and sets a new object with 2 keys
.then(result => { //if insert is succesful, do something
console.log('Todo Added') //loging action
response.redirect('/') //redirect back to the root, ejs is re-rendered
}) //closing .then
.catch(error => console.error(error)) //catching any error
}) //ending post

app.put('/markComplete', (request, response) => {
db.collection('todos').updateOne({thing: request.body.itemFromJS},{
app.put('/markComplete', (request, response) => { //starts a PUT(update) method when the '/markComplete is passed in
db.collection('todos').updateOne({ thing: request.body.itemFromJS }, { //look in the db for one item matching the name of the item passed in from the main.js file that was clicked on
$set: {
completed: true
}
},{
sort: {_id: -1},
upsert: false
completed: true //set completed status of item to true
}
}, {
sort: { _id: -1 }, //moves item to the bottom of the list in the db
upsert: false //upsert is a mix of insertOne and update, if it's set to 'true' it will create a new item if it does no exists. When set to false, prevents insertion if item does not exists
})
.then(result => {
console.log('Marked Complete')
response.json('Marked Complete')
})
.catch(error => console.error(error))
.then(result => { //starts a .then if update was succesful
console.log('Marked Complete') //loging succesful completion
response.json('Marked Complete') //sending a response back to the sender
}) //closing .then
.catch(error => console.error(error)) //catching errors

})
}) //closing .put

app.put('/markUnComplete', (request, response) => {
db.collection('todos').updateOne({thing: request.body.itemFromJS},{
app.put('/markUnComplete', (request, response) => { //starts a PUT(update) method when the '/markComplete is passed in
db.collection('todos').updateOne({ thing: request.body.itemFromJS }, { //look in the db for one item matching the name of the item passed in from the main.js file that was clicked on
$set: {
completed: false
}
},{
sort: {_id: -1},
upsert: false
completed: false //set completed status of item to false
}
}, {
sort: { _id: -1 }, //moves item to the bottom of the list in the db
upsert: false //prevents insertion if item does not exists
})
.then(result => {
console.log('Marked Complete')
response.json('Marked Complete')
})
.catch(error => console.error(error))
.then(result => { //starts a .then if update was succesful
console.log('Marked Complete') //loging succesful completion
response.json('Marked Complete') //sending a response back to the sender
}) //closing .then
.catch(error => console.error(error)) //catching errors

})
}) //closing .put

app.delete('/deleteItem', (request, response) => {
db.collection('todos').deleteOne({thing: request.body.itemFromJS})
.then(result => {
console.log('Todo Deleted')
response.json('Todo Deleted')
})
.catch(error => console.error(error))
app.delete('/deleteItem', (request, response) => { //starts a delete method when the '/deleteItem' route is passed in
db.collection('todos').deleteOne({ thing: request.body.itemFromJS }) //looks inside the 'todos' collection for the one item that has a matching name from js file
.then(result => { //starts a .then if delete was succesful
console.log('Todo Deleted') //log completion
response.json('Todo Deleted') //sends response back to the sender
}) //closing .then
.catch(error => console.error(error)) //catching errors

})
}) //closing method

app.listen(process.env.PORT || PORT, ()=>{
console.log(`Server running on port ${PORT}`)
})
app.listen(process.env.PORT || PORT, () => { //setting up the port, either the port from the .env file or the port variable we set
console.log(`Server running on port ${PORT}`) //loging the running port
}) //end the listen method
Loading