diff --git a/README.md b/README.md index 493995c1..df689277 100644 --- a/README.md +++ b/README.md @@ -1,100 +1,33 @@ Assignment 2 - Short Stack: Basic Two-tier Web Application using HTML/CSS/JS and Node.js -=== -Due: September 11th, by 11:59 AM. +Aarsh Zadaphiya https://a2-aarshzadaphiya.glitch.me/ -This assignment aims to introduce you to creating a prototype two-tiered web application. -Your application will include the use of HTML, CSS, JavaScript, and Node.js functionality, with active communication between the client and the server over the life of a user session. - -Baseline Requirements ---- - -There is a large range of application areas and possibilities that meet these baseline requirements. -Try to make your application do something useful! A todo list, storing / retrieving high scores for a very simple game... have a little fun with it. - -Your application is required to implement the following functionalities: - -- a `Server` which not only serves files, but also maintains a tabular dataset with 3 or more fields related to your application -- a `Results` functionality which shows the entire dataset residing in the server's memory -- a `Form/Entry` functionality which allows a user to add or delete data items residing in the server's memory -- a `Server Logic` which, upon receiving new or modified "incoming" data, includes and uses a function that adds at least one additional derived field to this incoming data before integrating it with the existing dataset -- the `Derived field` for a new row of data must be computed based on fields already existing in the row. -For example, a `todo` dataset with `task`, `priority`, and `creation_date` may generate a new field `deadline` by looking at `creation_date` and `priority` - -Your application is required to demonstrate the use of the following concepts: - -HTML: -- One or more [HTML Forms](https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms), with any combination of form tags appropriate for the user input portion of the application -- A results page displaying all data currently available on the server. You will most likely use a `` tag for this, but `
+ + + + + + + + + + + + + + +
TaskDeadlinePriorityIndexRemaining DaysRemove
diff --git a/public/js/main.js b/public/js/main.js index a569258f..30d1ec8a 100644 --- a/public/js/main.js +++ b/public/js/main.js @@ -1,27 +1,70 @@ -// FRONT-END (CLIENT) JAVASCRIPT HERE - -const submit = async function( event ) { +const submit = async function (event) { // stop form submission from trying to load // a new .html page for displaying results... // this was the original browser behavior and still // remains to this day - event.preventDefault() - - const input = document.querySelector( '#yourname' ), - json = { yourname: input.value }, - body = JSON.stringify( json ) + event.preventDefault(); + let evt = event.target + let json = {} + if (evt.getAttribute('formaction') === '/submit'){ + json = { + tasks: document.querySelector("#taskName").value, + date: document.querySelector("#dueDate").value, + priority: document.querySelector("#taskPriority").value, + } + }else { + json={id:evt.getAttribute('id')} + } + + fetch(evt.getAttribute('formaction'), { + method: "POST", + body: JSON.stringify(json), + }).then(async function (response) { + let data = await response.json(); + + const tableparse = document.querySelector("tbody"); + tableparse.innerHTML = ""; + + let resultHTML = tableparse.innerHTML; + for (const key in data) { + if (data.hasOwnProperty(key)) { + const row = document.createElement("tr"); + row.id = data[key].id; + + // for loop for each cell + for (const cellKey in data[key]) { + const cell = document.createElement("td"); + if (cellKey === "daysRemaining") { + const daysRemainingCell = document.createElement("td"); + daysRemainingCell.innerText = data[key][cellKey]; + row.appendChild(daysRemainingCell); + } else { + cell.innerText = data[key][cellKey]; + row.appendChild(cell); + } + + } + + const deleteButton = document.createElement("button"); + deleteButton.innerText = "Delete"; + deleteButton.className = "my-deletebutton"; + deleteButton.formAction = '/delete' + deleteButton.id=data[key].id; + + deleteButton.onclick = submit - const response = await fetch( '/submit', { - method:'POST', - body - }) + const deleteCell = document.createElement("td"); + deleteCell.appendChild(deleteButton); + row.appendChild(deleteCell); - const text = await response.text() + tableparse.appendChild(row); - console.log( 'text:', text ) -} + } + } + }); +}; -window.onload = function() { - const button = document.querySelector("button"); +window.onload = function () { + const button = document.querySelector("button"); button.onclick = submit; -} \ No newline at end of file +}; \ No newline at end of file diff --git a/server.improved.js b/server.improved.js index 9ac27fb8..cc738f5d 100644 --- a/server.improved.js +++ b/server.improved.js @@ -1,74 +1,86 @@ -const http = require( 'http' ), - fs = require( 'fs' ), - // IMPORTANT: you must run `npm install` in the directory for this assignment - // to install the mime library if you're testing this on your local machine. - // However, Glitch will install it automatically by looking in your package.json - // file. - mime = require( 'mime' ), - dir = 'public/', - port = 3000 - -const appdata = [ - { 'model': 'toyota', 'year': 1999, 'mpg': 23 }, - { 'model': 'honda', 'year': 2004, 'mpg': 30 }, - { 'model': 'ford', 'year': 1987, 'mpg': 14} -] - -const server = http.createServer( function( request,response ) { - if( request.method === 'GET' ) { - handleGet( request, response ) - }else if( request.method === 'POST' ){ - handlePost( request, response ) +const http = require("http"), + fs = require("fs"), + // IMPORTANT: you must run `npm install` in the directory for this assignment + // to install the mime library if you're testing this on your local machine. + // However, Glitch will install it automatically by looking in your package.json + // file. + mime = require("mime"), + dir = "public/", + port = 3000; + +let appdata = []; +let counter = 0; + +const server = http.createServer(function (request, response) { + if (request.method === "GET") { + handleGet(request, response); + } else if (request.method === "POST") {`` + handlePost(request, response); } -}) +}); -const handleGet = function( request, response ) { - const filename = dir + request.url.slice( 1 ) +const handleGet = function (request, response) { + const filename = dir + request.url.slice(1); - if( request.url === '/' ) { - sendFile( response, 'public/index.html' ) - }else{ - sendFile( response, filename ) + if (request.url === "/") { + sendFile(response, "public/index.html"); + } else { + sendFile(response, filename); } +}; + +const handlePost = function (request, response) { + let dataString = ""; + + request.on("data", function (data) { + dataString += data; + }); + + request.on("end", function () { + if (request.url === '/submit') { //handle form requests + let newData = JSON.parse(dataString); + newData.id = appdata.length; + appdata.push(newData); + calculateDaysRemaining(appdata); + console.log(appdata); + } else if (request.url === '/delete'){ + let index = JSON.parse(dataString); + appdata.splice(parseInt(index.id), 1); + for(let idRst = 0; idRst < appdata.length; idRst++){ + appdata[idRst].id = idRst; + } + } + console.log(appdata) + response.writeHead(200, 'OK', { 'Content-Type': 'application/json' }); + response.write(JSON.stringify(appdata)); + response.end(); +}); } -const handlePost = function( request, response ) { - let dataString = '' - - request.on( 'data', function( data ) { - dataString += data - }) - - request.on( 'end', function() { - console.log( JSON.parse( dataString ) ) - - // ... do something with the data here!!! - - response.writeHead( 200, "OK", {'Content-Type': 'text/plain' }) - response.end('test') - }) -} - -const sendFile = function( response, filename ) { - const type = mime.getType( filename ) - - fs.readFile( filename, function( err, content ) { - - // if the error = null, then we've loaded the file successfully - if( err === null ) { - - // status code: https://httpstatuses.com - response.writeHeader( 200, { 'Content-Type': type }) - response.end( content ) - - }else{ - - // file not found, error code 404 - response.writeHeader( 404 ) - response.end( '404 Error: File Not Found' ) - - } - }) -} - -server.listen( process.env.PORT || port ) +const calculateDaysRemaining = (data) => { + const currentDate = new Date(); + for (const item of data) { + const dueDate = new Date(item.date); + const daysRemaining = Math.ceil((dueDate - currentDate) / (1000 * 60 * 60 * 24)); + item.daysRemaining = daysRemaining > 0 ? `${daysRemaining} days` : 'Expired'; + } +}; + +const sendFile = function (response, filename) { + const type = mime.getType(filename); + + fs.readFile(filename, function (err, content) { + // if the error = null, then we've loaded the file successfully + if (err === null) { + // status code: https://httpstatuses.com + response.writeHeader(200, { "Content-Type": type }); + response.end(content); + } else { + // file not found, error code 404 + response.writeHeader(404); + response.end("404 Error: File Not Found"); + } + }); +}; + +server.listen(process.env.PORT || port); \ No newline at end of file