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 to server.js and main.js #42

Open
wants to merge 5 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.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"description": "",
"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
38 changes: 38 additions & 0 deletions public/js/main.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,42 @@
/**
* Name: Todo List Express
* Description: This app allows you to
* - Create todo tasks and store them in MongoDB
* - Read through a collection of todo tasks and render todos to DOM
* - Update completed todos, display remaining amount of tasks
* - Delete completed todos
*
* Input a collection of todo tasks. For every completed task, click on the task, to indicate the task has been completed. To remove a task, click the trashcan icon. Increase your productivity by 10x by using Todo List Express.
*
* @author Leon Noel, Brian Schnee, Erika Teal, Bianca Togonon, Alondra Mora, Lucas Winkler, Alyssha Lewin, Jacob Asper, Dana Lee, Brenden D'Souza, Sebastian Ospina, Jesse Ranon, Alexis Aguilar, Pree Robertson
*/

// select each element with class ".fa-trash"
const deleteBtn = document.querySelectorAll('.fa-trash')
// select each span within an element with class ".item"
const item = document.querySelectorAll('.item span')
// select each span with class ".completed" within an element with class ".item"
const itemCompleted = document.querySelectorAll('.item span.completed')

// add a click event to every rendered elements delete icon
Array.from(deleteBtn).forEach((element)=>{
element.addEventListener('click', deleteItem)
})

// add a click event to every rendered element's span that contains todo text
Array.from(item).forEach((element)=>{
element.addEventListener('click', markComplete)
})

// add a click event to every element that has a class "completed"
Array.from(itemCompleted).forEach((element)=>{
element.addEventListener('click', markUnComplete)
})

/**
* Name: deleteItem
* Description: makes a DELETE request to server.js, which will delete a document from our db
*/
async function deleteItem(){
const itemText = this.parentNode.childNodes[1].innerText
try{
Expand All @@ -33,25 +56,40 @@ async function deleteItem(){
}
}

/**
* Name: markComplete
* Description: makes a PUT request to server.js, which will set completed property of db document to false. On page render, a class "completed" will be added to spans that contain todo text. This will add a line through the text and decrease the amount of todo's "Left to do"
*/
async function markComplete(){
// will select the innerText of the first span
const itemText = this.parentNode.childNodes[1].innerText

try{
// make a PUT request to our server and pass our itemText in the body of our request
const response = await fetch('markComplete', {
method: 'put',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'itemFromJS': itemText
})
})

// convert the response into json
const data = await response.json()
console.log(data)

// represents the current endpoint, reloads our page (which will fire a new GET request)
location.reload()

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

/**
* Name: markUnComplete
* Description: makes a PUT request to server.js, which will set completed property of db document to false. This will prevent the "completed" class from being added to todo text span on page render
*/
async function markUnComplete(){
const itemText = this.parentNode.childNodes[1].innerText
try{
Expand Down
61 changes: 45 additions & 16 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,67 +1,95 @@
// import express
const express = require('express')

// instantiate a new instance of an express app - allows you to use easy to use variable name app
const app = express()

// import mongodb and instantiate a new MongoClient instance which allows you to manipulate, create, and connect to a mongo db
const MongoClient = require('mongodb').MongoClient
const PORT = 2121
require('dotenv').config()

// stores port number - looks for env variable else = 2121
const PORT = process.env.PORT || 2121;

// enables the use of .env file
require('dotenv').config()

/**
* db - will represent mongodb database
* dbConnectionStr - allows us to connect to mongo atlas db
* dbName - database name
*/
let db,
dbConnectionStr = process.env.DB_STRING,
dbName = 'todo'

// connect app to mongoclient db
MongoClient.connect(dbConnectionStr, { useUnifiedTopology: true })
.then(client => {
console.log(`Connected to ${dbName} Database`)
// create a new db named 'todo'
db = client.db(dbName)
})

// set view engine to ejs, allows us to render data using ejs
app.set('view engine', 'ejs')
// sets up public folder that will serve files to client
app.use(express.static('public'))
// parses incoming requests with urlencoded payloads (in replace of body-parser)
app.use(express.urlencoded({ extended: true }))
// parses incoming JSON requests
app.use(express.json())


// define a GET request at default endpoint
app.get('/',async (request, response)=>{
// access db collection called 'todos', find documents and store them in an array
const todoItems = await db.collection('todos').find().toArray()

// count documents in db that have false as a value for key "completed"
const itemsLeft = await db.collection('todos').countDocuments({completed: false})

// pass todoItems and itemsLeft to index.ejs file in order to be rendered
response.render('index.ejs', { items: todoItems, left: itemsLeft })
// db.collection('todos').find().toArray()
// .then(data => {
// db.collection('todos').countDocuments({completed: false})
// .then(itemsLeft => {
// response.render('index.ejs', { items: data, left: itemsLeft })
// })
// })
// .catch(error => console.error(error))
})

// define a POST request at /addTodo endpoint, used to Create a new document
app.post('/addTodo', (request, response) => {
// add new document to do todos collection, todoItem property is pulled from our request body
db.collection('todos').insertOne({thing: request.body.todoItem, completed: false})
.then(result => {
console.log('Todo Added')
// redirect to base endpoint after a document is added to db
response.redirect('/')
})
.catch(error => console.error(error))
})

// define a PUT request at /markComplete endpoint, used to update a document
app.put('/markComplete', (request, response) => {
// update a document from the todos collection
db.collection('todos').updateOne({thing: request.body.itemFromJS},{
$set: {
// set the completed key to true (in our ejs, add a class "completed" to the span if "completed" key has a value of true)
completed: true
}
}
},{
// specifies the order of documents from a collection
sort: {_id: -1},
// makes sure a new document isnt created if the document isnt found in our db
upsert: false
})
.then(result => {
console.log('Marked Complete')
// respond with json if marked is completed
response.json('Marked Complete')
})
.catch(error => console.error(error))

})

// define a PUT request at /markComplete endpoint, used to update a document
app.put('/markUnComplete', (request, response) => {
// set the completed property of a document to false
db.collection('todos').updateOne({thing: request.body.itemFromJS},{
$set: {
completed: false
Expand All @@ -71,23 +99,24 @@ app.put('/markUnComplete', (request, response) => {
upsert: false
})
.then(result => {
console.log('Marked Complete')
response.json('Marked Complete')
console.log('Marked UnComplete')
response.json('Marked UnComplete')
})
.catch(error => console.error(error))

})

// add DELETE request to /deleteItem endpoint
app.delete('/deleteItem', (request, response) => {
// delete document from todos collection with key "thing"'s value as the text passed to the request
db.collection('todos').deleteOne({thing: request.body.itemFromJS})
.then(result => {
console.log('Todo Deleted')
response.json('Todo Deleted')
})
.catch(error => console.error(error))

})

app.listen(process.env.PORT || PORT, ()=>{
// create server and listen on PORT for requests
app.listen(PORT, ()=>{
console.log(`Server running on port ${PORT}`)
})
1 change: 0 additions & 1 deletion views/index.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
<input type="submit">
</form>


<script src='js/main.js'></script>
</body>
</html>