Advertisement
Guest User

Untitled

a guest
Apr 26th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.60 KB | None | 0 0
  1. /****************************************************************/
  2. /************* INITIALISATION ***********************************/
  3. /****************************************************************/
  4. let express = require('express');
  5. let path = require('path');
  6. let bodyParser = require('body-parser');
  7. let mysql = require('mysql');
  8.  
  9. let app = express();
  10.  
  11. // Define the static folder
  12. app.use(express.static(path.join(__dirname, 'public')));
  13.  
  14. // Neded for parsing json data
  15. app.use(bodyParser.json());
  16.  
  17. // Inform that server is alive
  18. console.log("Server running on 8080.");
  19.  
  20. // Listen to a port
  21. app.listen(8080);
  22.  
  23. /****************************************************************/
  24. /************* DATABASE QUERY ***********************************/
  25. /****************************************************************/
  26. // define an object with connection parameters
  27. const CONNECTION_PARAMETERS = {
  28. host: "localhost",
  29. port: 55555,
  30. user: "root",
  31. password: "sa",
  32. database: "firstdb"
  33. };
  34. /**
  35. * Runs a query.
  36. * @param {object} conParam - The object with connection parameters.
  37. * @param {string} sql - The sql query.
  38. * @returns {[object]} An array with results.
  39. * @throws {error} An error resulting from interaction with database.
  40. */
  41. function performDatabaseQuery(conParam, sql) {
  42. return new Promise(function (resolve, reject) {
  43. // create a connection to db
  44. let con = mysql.createConnection(CONNECTION_PARAMETERS);
  45. // open the connection
  46. con.connect(function (err) {
  47. // if connection error occurs, the client must be informed
  48. if (err) {
  49. reject(new Error("Eroare la conectarea la baza de date." + err.message));
  50. } else {
  51. // run query
  52. con.query(sql, function (err, result) {
  53.  
  54. if (err) {
  55. // if query error occurs, the client must be informed
  56. reject(new Error("Eroare la inserarea datelor." + err.message));
  57. } else {
  58. // if we are here => Hooray, no errors!
  59. resolve(result);
  60. }
  61. });
  62. }
  63. });
  64. });
  65. }
  66.  
  67. /****************************************************************/
  68. /************* DEFINE ROUTES ************************************/
  69. /****************************************************************/
  70. // post on /student
  71. app.post('/student', async function (req, res) {
  72. try {
  73. // get data from client request
  74. let student = {
  75. name: req.body.name,
  76. grade: req.body.grade
  77. };
  78. // data must be validated on the server
  79. testValidity(student);
  80. // prepare the insert query
  81. let sql = "INSERT INTO students (name, grade) VALUES ('" + student.name + "','" + student.grade + "');";
  82. // run query
  83. await performDatabaseQuery(CONNECTION_PARAMETERS, sql);
  84. // inform the client about successful operation
  85. res.status(200).send();
  86. } catch (err) {
  87. // inform the client about errors
  88. res.status(500).send("Eroare server." + err.message);
  89. throw err;
  90. }
  91. });
  92.  
  93. app.put('/student', async function (req, res) {
  94. try {
  95. // get data from client request
  96. let student = {
  97. name: req.body.name,
  98. grade: req.body.grade,
  99. id: req.body.id
  100. };
  101. // data must be validated on the server
  102. //testValidity(student);
  103. // prepare the insert query
  104. let sql = "UPDATE students SET name = '"+student.name+"', grade ='"+student.grade+"' WHERE id="+student.id+";";
  105. // run query
  106. await performDatabaseQuery(CONNECTION_PARAMETERS, sql);
  107. // inform the client about successful operation
  108. res.status(200).send();
  109. } catch (err) {
  110. // inform the client about errors
  111. res.status(500).send("Eroare server." + err.message);
  112. throw err;
  113. }
  114. });
  115.  
  116. // get on /student
  117. app.get('/student', async function (req, res) {
  118. try {
  119. // prepare the select query
  120. let sql = "SELECT * FROM students;";
  121. // run query
  122. let result = await performDatabaseQuery(CONNECTION_PARAMETERS, sql);
  123. // inform the client about successful operation
  124. res.status(200).send(result);
  125. } catch (err) {
  126. // inform the client about errors
  127. res.status(500).send("Eroare server." + err.message);
  128. throw err;
  129. }
  130. });
  131. // delete on /student
  132. app.delete('/student', async function (req, res) {
  133. try {
  134. // get data from client request
  135. let id = req.body.id;
  136. // prepare the delete query
  137. let sql = "DELETE FROM students WHERE id = " + id + ";";
  138. console.log(sql);
  139. // run query
  140. await performDatabaseQuery(CONNECTION_PARAMETERS, sql);
  141. // inform the client about successful operation
  142. res.status(200).send();
  143. } catch (err) {
  144. // inform the client about errors
  145. res.status(500).send("Eroare server." + err.message);
  146. throw err;
  147. }
  148. });
  149. /****************************************************************/
  150. /************* VALIDATION FUNCTIONS *****************************/
  151. /****************************************************************/
  152. // private constants for validation
  153. const NAME_MIN_LENGTH = 3;
  154. const NAME_MAX_LENGTH = 100;
  155. const GRADE_MIN_VALUE = 1;
  156. const GRADE_MAX_VALUE = 10;
  157. /**
  158. * Test the validity of a student (name and grade).
  159. * @param {object} student - The student to be validated.
  160. * @throws {error} An error resulting from validation.
  161. */
  162. function testValidity(student) {
  163. let errorMessages = "";
  164. if (typeof student.name === "undefined" || student.name === null || student.name.length < NAME_MIN_LENGTH || student.name.length > NAME_MAX_LENGTH) {
  165. errorMessages += "Name should have at least three characters and should not exceed fifty characters.";
  166. }
  167. if (typeof student.grade === "undefined" || student.grade === null || isNaN(student.grade) || student.age < GRADE_MIN_VALUE || student.grade > GRADE_MAX_VALUE) {
  168. errorMessages += "Grade should be a number between 1 and 10.";
  169. }
  170. if (errorMessages) {
  171. throw new Error(errorMessages);
  172. }
  173. }
  174.  
  175.  
  176.  
  177.  
  178.  
  179.  
  180.  
  181.  
  182.  
  183.  
  184.  
  185.  
  186.  
  187.  
  188.  
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.  
  203.  
  204.  
  205.  
  206. <!DOCTYPE html>
  207. <html>
  208. <head>
  209. <title>StudentWebApp - Create and Update</title>
  210. <meta charset="utf-8" />
  211. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  212. <meta name="description" content="SPA MVC REST Web App">
  213. <meta name="keywords" content="HTML,CSS,XML,JavaScript">
  214. <meta name="author" content="Ovidiu Schipor">
  215. <link rel="stylesheet" type="text/css" href="Css/Reset.css" />
  216. <link rel="stylesheet" type="text/css" href="Css/View.css" />
  217. <script src="Js/clientModel.js"></script>
  218. <script src="Js/clientController.js"></script>
  219. </head>
  220. <body>
  221. <header>
  222. <img src="Img/logo.png" alt="application logo" /><h1>Students management app</h1>
  223. </header>
  224. <nav>
  225. <ul id="navTabs">
  226. <li id="btnShowStudentPage">Create / Update</li>
  227. <li id="btnShowStudentsPage">Read / Delete</li>
  228. <li id="btnShowLoginPage">Login / Logout</li>
  229. </ul>
  230. </nav>
  231. <main>
  232. <!-- User Message Box -->
  233. <aside id="boxMessage" class="error">
  234. <span id="lblMessage"></span>
  235. <span id="btnHideMessageBox">&times;</span>
  236. </aside>
  237. <!-- Create Update Page -->
  238. <section id="pgStudent">
  239. <h2>Student information</h2>
  240. <form>
  241. <ul>
  242. <li>
  243. <label for="txtStudentName">What's your name?
  244. <abbr title="required">*</abbr></label>
  245. <input type="text" id="txtStudentName" placeholder="your name" />
  246. </li>
  247. <li>
  248. <label for="txtStudentGrade">What's your grade? <abbr title="required">*</abbr></label>
  249. <input type="text" id="txtStudentGrade" placeholder="your grade" />
  250. </li>
  251. <li>
  252. <input type="hidden" id="txtStudentId" value="">
  253. <input type="button" id="btnSubmitStudent" value="Send information" />
  254. </li>
  255. <li>
  256. <input type="reset" id="btnResetStudent" value="Reset information" />
  257. </li>
  258. </ul>
  259. <small>All fields marked with an asterisk (*) are required.</small>
  260. </form>
  261. </section>
  262. <!-- Read Delete Page -->
  263. <section id="pgStudents">
  264. <h2>Students list</h2>
  265. <table>
  266. <thead>
  267. <tr>
  268. <th>Id</th>
  269. <th>Name</th>
  270. <th>Grade</th>
  271. <th>Update</th>
  272. <th>Delete</th>
  273. </tr>
  274. </thead>
  275. <tbody id="studentsList">
  276.  
  277. </tbody>
  278. </table>
  279. </section>
  280. <!-- Login Page -->
  281. <section id="pgLogin">
  282. <h2>Login page</h2>
  283. <ul>
  284. <li>
  285. <label for="txtLoginUser">What's your username?</label>
  286. <input type="text" id="txtLoginUser" placeholder="your username" />
  287. </li>
  288. <li>
  289. <label for="txtLoginPass">What's your password?</label>
  290. <input type="password" id="txtLoginPass" placeholder="your password" />
  291. </li>
  292. <li>
  293. <input type="button" id="btnLogin" value="Login" />
  294. <input type="button" id="btnLogout" value="Logout" />
  295. </li>
  296. </ul>
  297. </section>
  298. </main>
  299. <footer>
  300. <small>Copyright "Ștefan cel Mare" University of Suceava</small>
  301. </footer>
  302. </body>
  303. </html>
  304.  
  305.  
  306.  
  307.  
  308.  
  309.  
  310.  
  311.  
  312.  
  313.  
  314.  
  315.  
  316.  
  317.  
  318.  
  319.  
  320.  
  321.  
  322.  
  323.  
  324.  
  325.  
  326.  
  327.  
  328.  
  329.  
  330. /****************************************************************/
  331. /************* INITIALISATION ***********************************/
  332. /****************************************************************/
  333.  
  334. // when whole DOM of html page was loaded, call the init function
  335. document.addEventListener("DOMContentLoaded", init);
  336.  
  337. /**
  338. * A shortcut for a html element (dom = document object model).
  339. * @param {string} id - The id of html element.
  340. * @returns {object} The html element with specified id.
  341. */
  342. function dom(id) {
  343. return document.getElementById(id);
  344. }
  345.  
  346. /**
  347. * Called when whole DOM of html page was loaded.
  348. * Performs connection between events and handler functions.
  349. * Application will starts with Student Page.
  350. */
  351. function init() {
  352. dom("btnShowStudentPage").addEventListener("click", showStudentPage);
  353. dom("btnShowStudentsPage").addEventListener("click", showStudentsPage);
  354. dom("btnShowLoginPage").addEventListener("click", showLoginPage);
  355. dom("btnHideMessageBox").addEventListener("click", hideMessageBox);
  356. dom("btnSubmitStudent").addEventListener("click", saveStudent);
  357. showStudentPage();
  358. }
  359.  
  360. /****************************************************************/
  361. /************* HANDLE INTERFACE *********************************/
  362. /****************************************************************/
  363. /**
  364. * Hides all pages of application.
  365. */
  366. function hideAllPages() {
  367. dom("pgStudent").style.display = "none";
  368. dom("pgStudents").style.display = "none";
  369. dom("pgLogin").style.display = "none";
  370. }
  371. /**
  372. * Shows the Student Page wile hiding all others pages.
  373. */
  374. function showStudentPage() {
  375. hideAllPages();
  376. dom("pgStudent").style.display = "block";
  377. }
  378. /**
  379. * Resets the Student Page by setting all the values to empty data.
  380. */
  381. function resetStudentPage() {
  382. dom("txtStudentName").value = "";
  383. dom("txtStudentGrade").value = "";
  384. }
  385. /**
  386. * Shows the Students Page wile hiding all others pages.
  387. */
  388. function showStudentsPage() {
  389. hideAllPages();
  390. dom("pgStudents").style.display = "block";
  391. getStudents();
  392. }
  393. /**
  394. * Shows the Login Page wile hiding all others pages.
  395. */
  396. function showLoginPage() {
  397. hideAllPages();
  398. dom("pgLogin").style.display = "block";
  399. }
  400. /**
  401. * Shows the Message Box with a specific message, using a color for error.
  402. * @param {string} message - The message to be displayed.
  403. */
  404. function showErrorMessage(message) {
  405. dom("lblMessage").innerHTML = message;
  406. dom("boxMessage").className = "error";
  407. dom("boxMessage").style.display = "block";
  408. }
  409. /**
  410. * Shows the Message Box with a specific message, using a color for success.
  411. * @param {string} message - The message to be displayed.
  412. */
  413. function showSuccessMessage(message) {
  414. dom("lblMessage").innerHTML = message;
  415. dom("boxMessage").className = "success";
  416. dom("boxMessage").style.display = "block";
  417. }
  418. /**
  419. * Closes the Message Page.
  420. */
  421. function hideMessageBox() {
  422. dom("boxMessage").style.display = "none";
  423. }
  424.  
  425. /****************************************************************/
  426. /************* COMMUNICATE WITH SERVER **************************/
  427. /****************************************************************/
  428. /**
  429. * Tries to save the student by sending it to the server.
  430. */
  431. async function saveStudent() {
  432. try {
  433. let name = dom("txtStudentName").value;
  434. let grade = dom("txtStudentGrade").value;
  435. let id = dom("txtStudentId").value;
  436. let student = {
  437. name: name,
  438. grade: grade,
  439. id : id
  440. };
  441. testValidity(student);
  442. if(id!=''){
  443. await performHttpRequest("PUT", STUDENT_ROUTE, student);
  444. showSuccessMessage("Update-ul s-a realizat cu succes");
  445. }else{
  446. await performHttpRequest("POST", STUDENT_ROUTE, student);
  447. showSuccessMessage("Salvarea s-a realizat cu succes");
  448. }
  449.  
  450.  
  451. } catch (err) {
  452. showErrorMessage(err);
  453. throw err;
  454. }
  455. }
  456. /**
  457. * Tries to get all the student from the server and inject them to html.
  458. */
  459. async function getStudents() {
  460. try {
  461. let result = await performHttpRequest("GET", STUDENT_ROUTE);
  462. let students = JSON.parse(result);
  463. // create a string with HTML code for table's rows
  464. let html = "";
  465. for (let i = 0; i < students.length; i++) {
  466. html += "<tr><td>" + students[i].id + "</td>" +
  467. "<td>" + students[i].name + "</td>" +
  468. "<td>" + students[i].grade + "</td>" +
  469. "<td class='update' onclick='updateStudent(this.parentElement)'></td>" +
  470. "<td class='delete' onclick='deleteStudent(this.parentElement)'></td></tr>";
  471. }
  472. // inject students in the Students Page's table
  473. dom("studentsList").innerHTML = html;
  474. } catch (err) {
  475. showErrorMessage(err);
  476. }
  477. }
  478. /**
  479. * Tries to delete the student by sending its id to the server.
  480. * @param {HTML Element} row - The table row representing the student.
  481. */
  482. async function deleteStudent(row) {
  483. try {
  484. let id = row.childNodes[0].innerHTML;
  485. let student = {
  486. id: id
  487. };
  488. await performHttpRequest("DELETE", STUDENT_ROUTE, student);
  489. showSuccessMessage("Stergerea s-a realizat cu succes");
  490. getStudents();
  491. } catch (err) {
  492. showErrorMessage(err);
  493. throw err;
  494. }
  495. }
  496.  
  497. async function updateStudent(row) {
  498. try {
  499. let id = row.childNodes[0].innerHTML;
  500. let name = row.childNodes[1].innerHTML;
  501. let grade = row.childNodes[2].innerHTML;
  502.  
  503. //alert(id + name + grade);
  504.  
  505. dom("txtStudentId").value = id;
  506. dom("txtStudentName").value = name;
  507. dom("txtStudentGrade").value = grade;
  508. showStudentPage();
  509.  
  510. } catch (err) {
  511. showErrorMessage(err);
  512. throw err;
  513. }
  514. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement