Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /****************************************************************/
- /************* INITIALISATION ***********************************/
- /****************************************************************/
- let express = require('express');
- let path = require('path');
- let bodyParser = require('body-parser');
- let mysql = require('mysql');
- let app = express();
- // Define the static folder
- app.use(express.static(path.join(__dirname, 'public')));
- // Neded for parsing json data
- app.use(bodyParser.json());
- // Inform that server is alive
- console.log("Server running on 8080.");
- // Listen to a port
- app.listen(8080);
- /****************************************************************/
- /************* DATABASE QUERY ***********************************/
- /****************************************************************/
- // define an object with connection parameters
- const CONNECTION_PARAMETERS = {
- host: "localhost",
- port: 55555,
- user: "root",
- password: "sa",
- database: "firstdb"
- };
- /**
- * Runs a query.
- * @param {object} conParam - The object with connection parameters.
- * @param {string} sql - The sql query.
- * @returns {[object]} An array with results.
- * @throws {error} An error resulting from interaction with database.
- */
- function performDatabaseQuery(conParam, sql) {
- return new Promise(function (resolve, reject) {
- // create a connection to db
- let con = mysql.createConnection(CONNECTION_PARAMETERS);
- // open the connection
- con.connect(function (err) {
- // if connection error occurs, the client must be informed
- if (err) {
- reject(new Error("Eroare la conectarea la baza de date." + err.message));
- } else {
- // run query
- con.query(sql, function (err, result) {
- if (err) {
- // if query error occurs, the client must be informed
- reject(new Error("Eroare la inserarea datelor." + err.message));
- } else {
- // if we are here => Hooray, no errors!
- resolve(result);
- }
- });
- }
- });
- });
- }
- /****************************************************************/
- /************* DEFINE ROUTES ************************************/
- /****************************************************************/
- // post on /student
- app.post('/student', async function (req, res) {
- try {
- // get data from client request
- let student = {
- name: req.body.name,
- grade: req.body.grade
- };
- // data must be validated on the server
- testValidity(student);
- // prepare the insert query
- let sql = "INSERT INTO students (name, grade) VALUES ('" + student.name + "','" + student.grade + "');";
- // run query
- await performDatabaseQuery(CONNECTION_PARAMETERS, sql);
- // inform the client about successful operation
- res.status(200).send();
- } catch (err) {
- // inform the client about errors
- res.status(500).send("Eroare server." + err.message);
- throw err;
- }
- });
- app.put('/student', async function (req, res) {
- try {
- // get data from client request
- let student = {
- name: req.body.name,
- grade: req.body.grade,
- id: req.body.id
- };
- // data must be validated on the server
- //testValidity(student);
- // prepare the insert query
- let sql = "UPDATE students SET name = '"+student.name+"', grade ='"+student.grade+"' WHERE id="+student.id+";";
- // run query
- await performDatabaseQuery(CONNECTION_PARAMETERS, sql);
- // inform the client about successful operation
- res.status(200).send();
- } catch (err) {
- // inform the client about errors
- res.status(500).send("Eroare server." + err.message);
- throw err;
- }
- });
- // get on /student
- app.get('/student', async function (req, res) {
- try {
- // prepare the select query
- let sql = "SELECT * FROM students;";
- // run query
- let result = await performDatabaseQuery(CONNECTION_PARAMETERS, sql);
- // inform the client about successful operation
- res.status(200).send(result);
- } catch (err) {
- // inform the client about errors
- res.status(500).send("Eroare server." + err.message);
- throw err;
- }
- });
- // delete on /student
- app.delete('/student', async function (req, res) {
- try {
- // get data from client request
- let id = req.body.id;
- // prepare the delete query
- let sql = "DELETE FROM students WHERE id = " + id + ";";
- console.log(sql);
- // run query
- await performDatabaseQuery(CONNECTION_PARAMETERS, sql);
- // inform the client about successful operation
- res.status(200).send();
- } catch (err) {
- // inform the client about errors
- res.status(500).send("Eroare server." + err.message);
- throw err;
- }
- });
- /****************************************************************/
- /************* VALIDATION FUNCTIONS *****************************/
- /****************************************************************/
- // private constants for validation
- const NAME_MIN_LENGTH = 3;
- const NAME_MAX_LENGTH = 100;
- const GRADE_MIN_VALUE = 1;
- const GRADE_MAX_VALUE = 10;
- /**
- * Test the validity of a student (name and grade).
- * @param {object} student - The student to be validated.
- * @throws {error} An error resulting from validation.
- */
- function testValidity(student) {
- let errorMessages = "";
- if (typeof student.name === "undefined" || student.name === null || student.name.length < NAME_MIN_LENGTH || student.name.length > NAME_MAX_LENGTH) {
- errorMessages += "Name should have at least three characters and should not exceed fifty characters.";
- }
- if (typeof student.grade === "undefined" || student.grade === null || isNaN(student.grade) || student.age < GRADE_MIN_VALUE || student.grade > GRADE_MAX_VALUE) {
- errorMessages += "Grade should be a number between 1 and 10.";
- }
- if (errorMessages) {
- throw new Error(errorMessages);
- }
- }
- <!DOCTYPE html>
- <html>
- <head>
- <title>StudentWebApp - Create and Update</title>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta name="description" content="SPA MVC REST Web App">
- <meta name="keywords" content="HTML,CSS,XML,JavaScript">
- <meta name="author" content="Ovidiu Schipor">
- <link rel="stylesheet" type="text/css" href="Css/Reset.css" />
- <link rel="stylesheet" type="text/css" href="Css/View.css" />
- <script src="Js/clientModel.js"></script>
- <script src="Js/clientController.js"></script>
- </head>
- <body>
- <header>
- <img src="Img/logo.png" alt="application logo" /><h1>Students management app</h1>
- </header>
- <nav>
- <ul id="navTabs">
- <li id="btnShowStudentPage">Create / Update</li>
- <li id="btnShowStudentsPage">Read / Delete</li>
- <li id="btnShowLoginPage">Login / Logout</li>
- </ul>
- </nav>
- <main>
- <!-- User Message Box -->
- <aside id="boxMessage" class="error">
- <span id="lblMessage"></span>
- <span id="btnHideMessageBox">×</span>
- </aside>
- <!-- Create Update Page -->
- <section id="pgStudent">
- <h2>Student information</h2>
- <form>
- <ul>
- <li>
- <label for="txtStudentName">What's your name?
- <abbr title="required">*</abbr></label>
- <input type="text" id="txtStudentName" placeholder="your name" />
- </li>
- <li>
- <label for="txtStudentGrade">What's your grade? <abbr title="required">*</abbr></label>
- <input type="text" id="txtStudentGrade" placeholder="your grade" />
- </li>
- <li>
- <input type="hidden" id="txtStudentId" value="">
- <input type="button" id="btnSubmitStudent" value="Send information" />
- </li>
- <li>
- <input type="reset" id="btnResetStudent" value="Reset information" />
- </li>
- </ul>
- <small>All fields marked with an asterisk (*) are required.</small>
- </form>
- </section>
- <!-- Read Delete Page -->
- <section id="pgStudents">
- <h2>Students list</h2>
- <table>
- <thead>
- <tr>
- <th>Id</th>
- <th>Name</th>
- <th>Grade</th>
- <th>Update</th>
- <th>Delete</th>
- </tr>
- </thead>
- <tbody id="studentsList">
- </tbody>
- </table>
- </section>
- <!-- Login Page -->
- <section id="pgLogin">
- <h2>Login page</h2>
- <ul>
- <li>
- <label for="txtLoginUser">What's your username?</label>
- <input type="text" id="txtLoginUser" placeholder="your username" />
- </li>
- <li>
- <label for="txtLoginPass">What's your password?</label>
- <input type="password" id="txtLoginPass" placeholder="your password" />
- </li>
- <li>
- <input type="button" id="btnLogin" value="Login" />
- <input type="button" id="btnLogout" value="Logout" />
- </li>
- </ul>
- </section>
- </main>
- <footer>
- <small>Copyright "Ștefan cel Mare" University of Suceava</small>
- </footer>
- </body>
- </html>
- /****************************************************************/
- /************* INITIALISATION ***********************************/
- /****************************************************************/
- // when whole DOM of html page was loaded, call the init function
- document.addEventListener("DOMContentLoaded", init);
- /**
- * A shortcut for a html element (dom = document object model).
- * @param {string} id - The id of html element.
- * @returns {object} The html element with specified id.
- */
- function dom(id) {
- return document.getElementById(id);
- }
- /**
- * Called when whole DOM of html page was loaded.
- * Performs connection between events and handler functions.
- * Application will starts with Student Page.
- */
- function init() {
- dom("btnShowStudentPage").addEventListener("click", showStudentPage);
- dom("btnShowStudentsPage").addEventListener("click", showStudentsPage);
- dom("btnShowLoginPage").addEventListener("click", showLoginPage);
- dom("btnHideMessageBox").addEventListener("click", hideMessageBox);
- dom("btnSubmitStudent").addEventListener("click", saveStudent);
- showStudentPage();
- }
- /****************************************************************/
- /************* HANDLE INTERFACE *********************************/
- /****************************************************************/
- /**
- * Hides all pages of application.
- */
- function hideAllPages() {
- dom("pgStudent").style.display = "none";
- dom("pgStudents").style.display = "none";
- dom("pgLogin").style.display = "none";
- }
- /**
- * Shows the Student Page wile hiding all others pages.
- */
- function showStudentPage() {
- hideAllPages();
- dom("pgStudent").style.display = "block";
- }
- /**
- * Resets the Student Page by setting all the values to empty data.
- */
- function resetStudentPage() {
- dom("txtStudentName").value = "";
- dom("txtStudentGrade").value = "";
- }
- /**
- * Shows the Students Page wile hiding all others pages.
- */
- function showStudentsPage() {
- hideAllPages();
- dom("pgStudents").style.display = "block";
- getStudents();
- }
- /**
- * Shows the Login Page wile hiding all others pages.
- */
- function showLoginPage() {
- hideAllPages();
- dom("pgLogin").style.display = "block";
- }
- /**
- * Shows the Message Box with a specific message, using a color for error.
- * @param {string} message - The message to be displayed.
- */
- function showErrorMessage(message) {
- dom("lblMessage").innerHTML = message;
- dom("boxMessage").className = "error";
- dom("boxMessage").style.display = "block";
- }
- /**
- * Shows the Message Box with a specific message, using a color for success.
- * @param {string} message - The message to be displayed.
- */
- function showSuccessMessage(message) {
- dom("lblMessage").innerHTML = message;
- dom("boxMessage").className = "success";
- dom("boxMessage").style.display = "block";
- }
- /**
- * Closes the Message Page.
- */
- function hideMessageBox() {
- dom("boxMessage").style.display = "none";
- }
- /****************************************************************/
- /************* COMMUNICATE WITH SERVER **************************/
- /****************************************************************/
- /**
- * Tries to save the student by sending it to the server.
- */
- async function saveStudent() {
- try {
- let name = dom("txtStudentName").value;
- let grade = dom("txtStudentGrade").value;
- let id = dom("txtStudentId").value;
- let student = {
- name: name,
- grade: grade,
- id : id
- };
- testValidity(student);
- if(id!=''){
- await performHttpRequest("PUT", STUDENT_ROUTE, student);
- showSuccessMessage("Update-ul s-a realizat cu succes");
- }else{
- await performHttpRequest("POST", STUDENT_ROUTE, student);
- showSuccessMessage("Salvarea s-a realizat cu succes");
- }
- } catch (err) {
- showErrorMessage(err);
- throw err;
- }
- }
- /**
- * Tries to get all the student from the server and inject them to html.
- */
- async function getStudents() {
- try {
- let result = await performHttpRequest("GET", STUDENT_ROUTE);
- let students = JSON.parse(result);
- // create a string with HTML code for table's rows
- let html = "";
- for (let i = 0; i < students.length; i++) {
- html += "<tr><td>" + students[i].id + "</td>" +
- "<td>" + students[i].name + "</td>" +
- "<td>" + students[i].grade + "</td>" +
- "<td class='update' onclick='updateStudent(this.parentElement)'></td>" +
- "<td class='delete' onclick='deleteStudent(this.parentElement)'></td></tr>";
- }
- // inject students in the Students Page's table
- dom("studentsList").innerHTML = html;
- } catch (err) {
- showErrorMessage(err);
- }
- }
- /**
- * Tries to delete the student by sending its id to the server.
- * @param {HTML Element} row - The table row representing the student.
- */
- async function deleteStudent(row) {
- try {
- let id = row.childNodes[0].innerHTML;
- let student = {
- id: id
- };
- await performHttpRequest("DELETE", STUDENT_ROUTE, student);
- showSuccessMessage("Stergerea s-a realizat cu succes");
- getStudents();
- } catch (err) {
- showErrorMessage(err);
- throw err;
- }
- }
- async function updateStudent(row) {
- try {
- let id = row.childNodes[0].innerHTML;
- let name = row.childNodes[1].innerHTML;
- let grade = row.childNodes[2].innerHTML;
- //alert(id + name + grade);
- dom("txtStudentId").value = id;
- dom("txtStudentName").value = name;
- dom("txtStudentGrade").value = grade;
- showStudentPage();
- } catch (err) {
- showErrorMessage(err);
- throw err;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement