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 #832

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
// }
68 changes: 36 additions & 32 deletions public/js/main.js
Original file line number Diff line number Diff line change
@@ -1,72 +1,76 @@
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') // variable for elements with trash can
const item = document.querySelectorAll('.item span') // variable for items
const itemCompleted = document.querySelectorAll('.item span.completed') // variable for items marked as completed

// event listeners for delete requests
Array.from(deleteBtn).forEach((element)=>{
element.addEventListener('click', deleteItem)
})

// event listeners for PUT requests /markCompleted
Array.from(item).forEach((element)=>{
element.addEventListener('click', markComplete)
})

// event listeners for PUT requests /markUnComplete
Array.from(itemCompleted).forEach((element)=>{
element.addEventListener('click', markUnComplete)
})

// delete request
async function deleteItem(){
const itemText = this.parentNode.childNodes[1].innerText
const itemText = this.parentNode.childNodes[1].innerText // text from the span
try{
const response = await fetch('deleteItem', {
method: 'delete',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'itemFromJS': itemText
const response = await fetch('deleteItem', { // making a request to server, route is /deleteItem
method: 'delete', // set method to delete
headers: {'Content-Type': 'application/json'}, // tells server to expect JSON
body: JSON.stringify({ // convert object into JSON string
'itemFromJS': itemText // setting content of body to the variable declared above, naming it 'itemFromJS'
})
})
const data = await response.json()
const data = await response.json() // returns a promise resolved to a JSON object
console.log(data)
location.reload()
location.reload() // refreshes page

}catch(err){
console.log(err)
console.log(err) // if there is an error it will be shown in the console
}
}

// PUT request
async function markComplete(){
const itemText = this.parentNode.childNodes[1].innerText
const itemText = this.parentNode.childNodes[1].innerText // text from the span
try{
const response = await fetch('markComplete', {
method: 'put',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'itemFromJS': itemText
const response = await fetch('markComplete', { // making a request to server, route /markComplete
method: 'put', // method set to put (update)
headers: {'Content-Type': 'application/json'}, // tells server to expect JSON
body: JSON.stringify({ // convert object into JSON string
'itemFromJS': itemText // setting content of body to the variable declared above, naming it 'itemFromJS'
})
})
const data = await response.json()
const data = await response.json() // returns a promise resolved to a JSON
console.log(data)
location.reload()
location.reload() // refreshes page

}catch(err){
console.log(err)
console.log(err) // if there is an error it will be shown in the console
}
}

// PUT request
async function markUnComplete(){
const itemText = this.parentNode.childNodes[1].innerText
const itemText = this.parentNode.childNodes[1].innerText // text from the span
try{
const response = await fetch('markUnComplete', {
method: 'put',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'itemFromJS': itemText
const response = await fetch('markUnComplete', { // making a request to server, route /markUnComplete
method: 'put', // method set to put (update)
headers: {'Content-Type': 'application/json'}, // tells server to expect JSON
body: JSON.stringify({ // convert object into JSON string
'itemFromJS': itemText // setting content of body to the variable declared above, naming it 'itemFromJS'
})
})
const data = await response.json()
const data = await response.json() // returns a promise resolved to a JSON
console.log(data)
location.reload()
location.reload() // refreshes page

}catch(err){
console.log(err)
console.log(err) // if there is an error it will be shown in the console
}
}
82 changes: 41 additions & 41 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
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() // calling Express
const MongoClient = require('mongodb').MongoClient // requiring MongoDB
const PORT = 2121 // port in local host
require('dotenv').config() // enables .env file


let db,
dbConnectionStr = process.env.DB_STRING,
dbName = 'todo'
let db, // declaring an empty 'db' variable (database)
dbConnectionStr = process.env.DB_STRING, // database connection string from .env
dbName = 'todo' // name of the database

// connecting to the database
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())
app.set('view engine', 'ejs') // setting up templating language as EJS
app.use(express.static('public')) // setting up the public folder for static pages
app.use(express.urlencoded({ extended: true })) // used to parse incoming requests with URL-encoded data (data submitted via HTML form). the parsed URL-encoded data is accessible through req.body
app.use(express.json()) // enables JSON parsing for incoming requests. the parsed JSON data is accessible through req.body


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 })
app.get('/',async (request, response)=>{ // get request for main page
const todoItems = await db.collection('todos').find().toArray() // all the documents in the 'todo' collection in an array
const itemsLeft = await db.collection('todos').countDocuments({completed: false}) // the number of documents with completed value of false
response.render('index.ejs', { items: todoItems, left: itemsLeft }) // sending the variables todoItems and itsmeLeft to EJS
// db.collection('todos').find().toArray()
// .then(data => {
// db.collection('todos').countDocuments({completed: false})
Expand All @@ -35,59 +35,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})
app.post('/addTodo', (request, response) => { // route comes from action on HTML form
db.collection('todos').insertOne({thing: request.body.todoItem, completed: false}) // adds a document into the 'todo' collection
.then(result => {
console.log('Todo Added')
response.redirect('/')
console.log('Todo Added') // msg in terminal
response.redirect('/') // refreshes page
})
.catch(error => console.error(error))
.catch(error => console.error(error)) // if there is an error it will be shown in terminal
})

app.put('/markComplete', (request, response) => {
app.put('/markComplete', (request, response) => { // route comes from main.js function
db.collection('todos').updateOne({thing: request.body.itemFromJS},{
$set: {
completed: true
completed: true // updates to true
}
},{
sort: {_id: -1},
sort: {_id: -1}, // grabs the first one if there are several
upsert: false
})
.then(result => {
console.log('Marked Complete')
response.json('Marked Complete')
console.log('Marked Complete') // msg in terminal
response.json('Marked Complete') // response sent to client
})
.catch(error => console.error(error))
.catch(error => console.error(error)) // if there is an error it will be shown in terminal

})

app.put('/markUnComplete', (request, response) => {
app.put('/markUnComplete', (request, response) => { // route comes from main.js function
db.collection('todos').updateOne({thing: request.body.itemFromJS},{
$set: {
completed: false
completed: false // updates to false
}
},{
sort: {_id: -1},
sort: {_id: -1}, // grabs the first one if there are several
upsert: false
})
.then(result => {
console.log('Marked Complete')
response.json('Marked Complete')
console.log('Marked Complete') // msg in terminal
response.json('Marked Complete') // response sent to client
})
.catch(error => console.error(error))
.catch(error => console.error(error)) // if there is an error it will be shown in terminal

})

app.delete('/deleteItem', (request, response) => {
db.collection('todos').deleteOne({thing: request.body.itemFromJS})
app.delete('/deleteItem', (request, response) => { // route comes from main.js function
db.collection('todos').deleteOne({thing: request.body.itemFromJS}) // deletes document in 'todo' collection
.then(result => {
console.log('Todo Deleted')
response.json('Todo Deleted')
console.log('Todo Deleted') // msg in terminal
response.json('Todo Deleted') // response sent to client
})
.catch(error => console.error(error))
.catch(error => console.error(error)) // if there is an error it will be shown in terminal

})

app.listen(process.env.PORT || PORT, ()=>{
console.log(`Server running on port ${PORT}`)
app.listen(process.env.PORT || PORT, ()=>{ // listening on port provided by hosting site, or local host 2121
console.log(`Server running on port ${PORT}`) // msg in terminal which port is being used
})
14 changes: 4 additions & 10 deletions views/index.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,11 @@
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Todo List: </h1>
<ul class="todoItems">
<% for(let i=0; i < items.length; i++) {%>
<!-- for loop to add all 'todo' db collection documents -->
<% for(let i=0; i < items.length; i++) {%>
<li class="item">
<% if(items[i].completed === true) {%>
<span class='completed'><%= items[i].thing %></span>
Expand All @@ -32,10 +24,12 @@
<% } %>
</ul>

<!-- number of documents with completed value of false -->
<h2>Left to do: <%= left %></h2>

<h2>Add A Todo:</h2>

<!-- adds new document to 'todo' db collection -->
<form action="/addTodo" method="POST">
<input type="text" placeholder="Thing To Do" name="todoItem">
<input type="submit">
Expand Down