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

Homework due class 44 #830

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: 3 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/*
{
"editor.fontSize": 42,
"terminal.integrated.fontSize": 62
}
}
*/
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
{
"name": "rap-name-api",
"version": "1.0.0",
"description": "",
"description": "npm install add DB_STRING to .env file",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
Expand Down
2 changes: 1 addition & 1 deletion public/css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ h1{
.completed{
color: gray;
text-decoration: line-through;
}
} /* if to-do list item has been clicked and had class of 'completed' added to it text color changes to gray and has a line put through it */
62 changes: 31 additions & 31 deletions public/js/main.js
Original file line number Diff line number Diff line change
@@ -1,70 +1,70 @@
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') //assigns all elements with trash can class to a variable
const item = document.querySelectorAll('.item span') //assigns all span elements with parent that has 'item' class to a variable
const itemCompleted = document.querySelectorAll('.item span.completed') //assigns all span elements with 'completed' class and parent that has 'item' class to a variable

Array.from(deleteBtn).forEach((element)=>{
element.addEventListener('click', deleteItem)
})
}) //creates array from all delete icons and adds click event to each item

Array.from(item).forEach((element)=>{
element.addEventListener('click', markComplete)
})
}) //creates array from all html elements with item class (items on to do list) and adds click event to each item

Array.from(itemCompleted).forEach((element)=>{
element.addEventListener('click', markUnComplete)
})
}) //creates array from all html elements with 'completed' class and adds click event to each item

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
async function deleteItem(){ //asynchronous function for delete click event
const itemText = this.parentNode.childNodes[1].innerText //sets text attached to delete icon to variable
try{ //declaring try block
const response = await fetch('deleteItem', { //creates response variable that awaits on a fetch to retrieve data from deleteItem route
method: 'delete', //tells server to delete something
headers: {'Content-Type': 'application/json'}, //tells server to expect JSON object in request
body: JSON.stringify({ //declare message content being passed, stringify content
'itemFromJS': itemText //setting content of body to the variable declared above, naming it 'itemFromJS'
})
})
const data = await response.json()
console.log(data)
location.reload()
const data = await response.json() //setting JSON response from delete request to a variable
console.log(data) //log result to console
location.reload() //refresh page

}catch(err){
console.log(err)
}catch(err){ //declaring catch block to display any errors thrown in try block
console.log(err) //log error to console
}
}

async function markComplete(){
const itemText = this.parentNode.childNodes[1].innerText
async function markComplete(){ //callback function for mark-complete click event
const itemText = this.parentNode.childNodes[1].innerText //sets text value of click event to variable
try{
const response = await fetch('markComplete', {
const response = await fetch('markComplete', { //fetching an update/put request
method: 'put',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'itemFromJS': itemText
'itemFromJS': itemText //sending above variable in body of request
})
})
const data = await response.json()
const data = await response.json() //setting JSON response from update/put request to a variable
console.log(data)
location.reload()
location.reload() //refresh page

}catch(err){
console.log(err)
}
}

async function markUnComplete(){
const itemText = this.parentNode.childNodes[1].innerText
async function markUnComplete(){ //callback function for mark-uncomplete click event
const itemText = this.parentNode.childNodes[1].innerText //sets text value of click event to variable
try{
const response = await fetch('markUnComplete', {
const response = await fetch('markUnComplete', { //fetching an update/put request
method: 'put',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'itemFromJS': itemText
'itemFromJS': itemText //sending above variable in body of request
})
})
const data = await response.json()
const data = await response.json() //setting JSON response from update/put request to a variable
console.log(data)
location.reload()
location.reload() //refresh page

}catch(err){
console.log(err)
Expand Down
71 changes: 36 additions & 35 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') //require app to use express module
const app = express() //set express function to variable "app"
const MongoClient = require('mongodb').MongoClient //assigns variable for methods associated with MongoClient and talking to our DB
const PORT = 2121 //hard-coded default port where server will be listening
require('dotenv').config() //allows us to look for variables inside the .env file


let db,
dbConnectionStr = process.env.DB_STRING,
dbName = 'todo'
let db, //database variable
dbConnectionStr = process.env.DB_STRING, //database connection string variable
dbName = 'todo' //set database name

MongoClient.connect(dbConnectionStr, { useUnifiedTopology: true })
.then(client => {
console.log(`Connected to ${dbName} Database`)
db = client.db(dbName)
MongoClient.connect(dbConnectionStr, { useUnifiedTopology: true }) //creating connection to MongoDB using our connection string
.then(client => { //waiting for connection and proceeding if connection is successful
console.log(`Connected to ${dbName} Database`) //logging message for successful DB connection
db = client.db(dbName) //assigning value to previously declared variable, contains a DB client factory method
})

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') //tells express the templating language is EJS
app.use(express.static('public')) //handles routing for static pages like main.js and css
app.use(express.urlencoded({ extended: true })) //tells express to encode/decode URLs where header matches content, 'extended' allows for arrays and objects
app.use(express.json()) //parses JSON content


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/read request for main page
const todoItems = await db.collection('todos').find().toArray() //go to database collection 'todos', find the documents, list them in an array and set this to a variable
const itemsLeft = await db.collection('todos').countDocuments({completed: false}) //counts number of documents with completed property set to false and assigns this number to a variable
response.render('index.ejs', { items: todoItems, left: itemsLeft }) //render HTML and send response object containing todoItems and itemsLeft variables

// db.collection('todos').find().toArray()
// .then(data => {
// db.collection('todos').countDocuments({completed: false})
Expand All @@ -35,23 +36,23 @@ 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) => { //Post/create request
db.collection('todos').insertOne({thing: request.body.todoItem, completed: false}) //adds document to 'todos' collection; sets form submission to property 'thing' and 'completed' property to false
.then(result => {
console.log('Todo Added')
response.redirect('/')
console.log('Todo Added') //sends confirmation to terminal that item was added
response.redirect('/') //refreshes page/creates new Read request with updated info
})
.catch(error => console.error(error))
})

app.put('/markComplete', (request, response) => {
db.collection('todos').updateOne({thing: request.body.itemFromJS},{
app.put('/markComplete', (request, response) => { //Update/put request
db.collection('todos').updateOne({thing: request.body.itemFromJS},{ //find document in 'todos' connected to markComplete click event in main.js
$set: {
completed: true
}
} //update completed property to 'true'
},{
sort: {_id: -1},
upsert: false
sort: {_id: -1},
upsert: false
})
.then(result => {
console.log('Marked Complete')
Expand All @@ -61,11 +62,11 @@ app.put('/markComplete', (request, response) => {

})

app.put('/markUnComplete', (request, response) => {
db.collection('todos').updateOne({thing: request.body.itemFromJS},{
app.put('/markUnComplete', (request, response) => { //Update/put request
db.collection('todos').updateOne({thing: request.body.itemFromJS},{ //find document in 'todos' connected to markUnComplete click event in main.js
$set: {
completed: false
}
} //update completed property to 'false'
},{
sort: {_id: -1},
upsert: false
Expand All @@ -78,8 +79,8 @@ app.put('/markUnComplete', (request, response) => {

})

app.delete('/deleteItem', (request, response) => {
db.collection('todos').deleteOne({thing: request.body.itemFromJS})
app.delete('/deleteItem', (request, response) => { //Delete request
db.collection('todos').deleteOne({thing: request.body.itemFromJS}) //find document in 'todos' connected to deleteItem click event in main.js
.then(result => {
console.log('Todo Deleted')
response.json('Todo Deleted')
Expand All @@ -90,4 +91,4 @@ app.delete('/deleteItem', (request, response) => {

app.listen(process.env.PORT || PORT, ()=>{
console.log(`Server running on port ${PORT}`)
})
}) //function for default port (set at beginning of server) or port provided by hosting website to listen for server.js
54 changes: 27 additions & 27 deletions views/index.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -8,37 +8,37 @@
<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> <!-- typo -->
<!DOCTYPE html> <!-- typo -->
<html lang="en"> <!-- typo -->
<head> <!-- typo -->
<meta charset="UTF-8"> <!-- typo -->
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- typo -->
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- typo -->
<title>Document</title> <!-- typo -->
</head> <!-- typo -->
<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++) {%>
<li class="item">
<% if(items[i].completed === true) {%>
<span class='completed'><%= items[i].thing %></span>
<% }else{ %>
<span><%= items[i].thing %></span>
<% } %>
<span class='fa fa-trash'></span>
</li>
<% } %>
</ul>
<h1>Todo List: </h1> <!-- Main title -->
<ul class="todoItems"> <!-- unordered list with class of 'todoItems'-->
<% for(let i=0; i < items.length; i++) {%> <!-- EJS for loop -->
<li class="item"> <!-- create list item with class of 'item' -->
<% if(items[i].completed === true) {%> <!-- conditional evaluating if 'completed' property of current item has value of 'true' -->
<span class='completed'><%= items[i].thing %></span> <!-- create span with class 'completed' and insert value of item's 'thing' property (to-do task)-->
<% }else{ %> <!-- EJS for else of if/else statement -->
<span><%= items[i].thing %></span> <!-- create span without class and insert to-do task-->
<% } %> <!-- EJS to close else statement -->
<span class='fa fa-trash'></span> <!-- create span containing trash icon -->
</li>
<% } %> <!-- closing bracket of EJS for loop -->
</ul>

<h2>Left to do: <%= left %></h2>
<h2>Left to do: <%= left %></h2> <!-- heading containing value of 'left' property value from server response object -->

<h2>Add A Todo:</h2>
<h2>Add A Todo:</h2> <!-- heading for form where you can add a todo item -->

<form action="/addTodo" method="POST">
<input type="text" placeholder="Thing To Do" name="todoItem">
<input type="submit">
<form action="/addTodo" method="POST"> <!-- create form with /addTodo route and request type specified as POST-->
<input type="text" placeholder="Thing To Do" name="todoItem"> <!-- create text input for typing in new to-do item; add name so we can reference text value later in JS files -->
<input type="submit"> <!-- create input for submitting form -->
</form>


Expand Down