Advertisement
Guest User

Untitled

a guest
May 15th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.54 KB | None | 0 0
  1. ////client
  2. /****************************************************************/
  3. /************* INITIALISATION ***********************************/
  4. /****************************************************************/
  5.  
  6. // when whole DOM of html page was loaded, call the init function
  7. document.addEventListener("DOMContentLoaded", init);
  8.  
  9. /**
  10. * A shortcut for a html element (dom = document object model).
  11. * @param {string} id - The id of html element.
  12. * @returns {object} The html element with specified id.
  13. */
  14. function dom(id) {
  15. return document.getElementById(id);
  16. }
  17.  
  18. /**
  19. * Called when whole DOM of html page was loaded.
  20. * Performs connection between events and handler functions.
  21. * Application will starts with Student Page.
  22. */
  23. function init() {
  24. dom("btnShowStudentPage").addEventListener("click", showStudentPage);
  25. dom("btnShowStudentsPage").addEventListener("click", showStudentsPage);
  26. dom("btnShowLoginPage").addEventListener("click", showLoginPage);
  27. dom("btnHideMessageBox").addEventListener("click", hideMessageBox);
  28. dom("btnSubmitStudent").addEventListener("click", saveStudent);
  29. showStudentPage();
  30. }
  31.  
  32. /****************************************************************/
  33. /************* HANDLE INTERFACE *********************************/
  34. /****************************************************************/
  35. /**
  36. * Hides all pages of application.
  37. */
  38. function hideAllPages() {
  39. dom("pgStudent").style.display = "none";
  40. dom("pgStudents").style.display = "none";
  41. dom("pgLogin").style.display = "none";
  42. dom("id").style.display = "none";
  43. }
  44. /**
  45. * Shows the Student Page wile hiding all others pages.
  46. */
  47. function showUpdatePage() {
  48. hideAllPages();
  49. dom("pgStudent").style.display = "block";
  50. dom("id").style.display = "block";
  51. }
  52.  
  53.  
  54. function showStudentPage() {
  55. resetStudentPage();
  56. hideAllPages();
  57. dom("pgStudent").style.display = "block";
  58. }
  59. /**
  60. * Resets the Student Page by setting all the values to empty data.
  61. */
  62. function resetStudentPage() {
  63. dom("txtStudentName").value = "";
  64. dom("txtStudentId").value = "";
  65. dom("txtStudentGrade").value = "";
  66. }
  67. /**
  68. * Shows the Students Page wile hiding all others pages.
  69. */
  70. function showStudentsPage() {
  71. hideAllPages();
  72. dom("pgStudents").style.display = "block";
  73. getStudents();
  74. }
  75. /**
  76. * Shows the Login Page wile hiding all others pages.
  77. */
  78. function showLoginPage() {
  79. hideAllPages();
  80. dom("pgLogin").style.display = "block";
  81. }
  82. /**
  83. * Shows the Message Box with a specific message, using a color for error.
  84. * @param {string} message - The message to be displayed.
  85. */
  86. function showErrorMessage(message) {
  87. dom("lblMessage").innerHTML = message;
  88. dom("boxMessage").className = "error";
  89. dom("boxMessage").style.display = "block";
  90. }
  91. /**
  92. * Shows the Message Box with a specific message, using a color for success.
  93. * @param {string} message - The message to be displayed.
  94. */
  95. function showSuccessMessage(message) {
  96. dom("lblMessage").innerHTML = message;
  97. dom("boxMessage").className = "success";
  98. dom("boxMessage").style.display = "block";
  99. }
  100. /**
  101. * Closes the Message Page.
  102. */
  103. function hideMessageBox() {
  104. dom("boxMessage").style.display = "none";
  105. }
  106.  
  107. /****************************************************************/
  108. /************* COMMUNICATE WITH SERVER **************************/
  109. /****************************************************************/
  110. /**
  111. * Tries to save the student by sending it to the server.
  112. */
  113. async function saveStudent() {
  114. try {
  115. let name = dom("txtStudentName").value;
  116. let grade = dom("txtStudentGrade").value;
  117. let id = dom("txtStudentId").value;
  118. let student = {
  119. name: name,
  120. grade: grade,
  121. id: id
  122. };
  123. if(id==""){
  124. testValidity(student);
  125. await performHttpRequest("POST", STUDENT_ROUTE, student);
  126. showSuccessMessage("Salvarea s-a realizat cu succes");
  127. }
  128. else
  129. {
  130. await performHttpRequest("PUT", STUDENT_ROUTE, student);
  131. showSuccessMessage("Actualizarea s-a realizat cu succes");
  132.  
  133. }
  134. } catch (err) {
  135. showErrorMessage(err);
  136. throw err;
  137. }
  138. }
  139. /**
  140. * Tries to get all the student from the server and inject them to html.
  141. */
  142. async function getStudents() {
  143. try {
  144. let result = await performHttpRequest("GET", STUDENT_ROUTE);
  145. let students = JSON.parse(result);
  146. // create a string with HTML code for table's rows
  147. let html = "";
  148. for (let i = 0; i < students.length; i++) {
  149. html += "<tr><td>" + students[i].id + "</td>" +
  150. "<td>" + students[i].name + "</td>" +
  151. "<td>" + students[i].grade + "</td>" +
  152. "<td class='update' onclick='updateStudent(this.parentElement)'></td>" +
  153. "<td class='delete' onclick='deleteStudent(this.parentElement)'></td></tr>";
  154. }
  155. // inject students in the Students Page's table
  156. dom("studentsList").innerHTML = html;
  157. } catch (err) {
  158. showErrorMessage(err);
  159. }
  160. }
  161. /**
  162. * Tries to delete the student by sending its id to the server.
  163. * @param {HTML Element} row - The table row representing the student.
  164. */
  165. async function deleteStudent(row) {
  166. try {
  167. let id = row.childNodes[0].innerHTML;
  168. let student = {
  169. id: id
  170. };
  171. await performHttpRequest("DELETE", STUDENT_ROUTE, student);
  172. showSuccessMessage("Stergerea s-a realizat cu succes");
  173. getStudents();
  174. } catch (err) {
  175. showErrorMessage(err);
  176. throw err;
  177. }
  178. }
  179. async function updateStudent(row) {
  180. showUpdatePage();
  181. try {
  182. let id = row.childNodes[0].innerHTML;
  183. let nume = row.childNodes[1].innerHTML;
  184. let nota = row.childNodes[2].innerHTML;
  185. dom("txtStudentId").value=id;
  186. dom("txtStudentName").value=nume;
  187. dom("txtStudentGrade").value=nota;
  188.  
  189. } catch (err) {
  190. showErrorMessage(err);
  191. throw err;
  192. }
  193. }
  194.  
  195. //server
  196. /****************************************************************/
  197. /************* INITIALISATION ***********************************/
  198. /****************************************************************/
  199. let express = require('express');
  200. let path = require('path');
  201. let bodyParser = require('body-parser');
  202. let mysql = require('mysql');
  203.  
  204. let app = express();
  205.  
  206. // Define the static folder
  207. app.use(express.static(path.join(__dirname, 'public')));
  208.  
  209. // Neded for parsing json data
  210. app.use(bodyParser.json());
  211.  
  212. // Inform that server is alive
  213. console.log("Server running on 8080.");
  214.  
  215. // Listen to a port
  216. app.listen(8080);
  217.  
  218. /****************************************************************/
  219. /************* DATABASE QUERY ***********************************/
  220. /****************************************************************/
  221. // define an object with connection parameters
  222. const CONNECTION_PARAMETERS = {
  223. host: "localhost",
  224. port: 55555,
  225. user: "root",
  226. password: "sa",
  227. database: "firstdb"
  228. };
  229. /**
  230. * Runs a query.
  231. * @param {object} conParam - The object with connection parameters.
  232. * @param {string} sql - The sql query.
  233. * @returns {[object]} An array with results.
  234. * @throws {error} An error resulting from interaction with database.
  235. */
  236. function performDatabaseQuery(conParam, sql) {
  237. return new Promise(function (resolve, reject) {
  238. // create a connection to db
  239. let con = mysql.createConnection(CONNECTION_PARAMETERS);
  240. // open the connection
  241. con.connect(function (err) {
  242. // if connection error occurs, the client must be informed
  243. if (err) {
  244. reject(new Error("Eroare la conectarea la baza de date." + err.message));
  245. } else {
  246. // run query
  247. con.query(sql, function (err, result) {
  248.  
  249. if (err) {
  250. // if query error occurs, the client must be informed
  251. reject(new Error("Eroare la inserarea datelor." + err.message));
  252. } else {
  253. // if we are here => Hooray, no errors!
  254. resolve(result);
  255. }
  256. });
  257. }
  258. });
  259. });
  260. }
  261.  
  262. /****************************************************************/
  263. /************* DEFINE ROUTES ************************************/
  264. /****************************************************************/
  265. // post on /student
  266. app.post('/student', async function (req, res) {
  267. try {
  268. // get data from client request
  269. let student = {
  270. name: req.body.name,
  271. grade: req.body.grade
  272. };
  273. // data must be validated on the server
  274. testValidity(student);
  275. // prepare the insert query
  276. let sql = "INSERT INTO students (name, grade) VALUES ('" + student.name + "','" + student.grade + "');";
  277. // run query
  278. await performDatabaseQuery(CONNECTION_PARAMETERS, sql);
  279. // inform the client about successful operation
  280. res.status(200).send();
  281. } catch (err) {
  282. // inform the client about errors
  283. res.status(500).send("Eroare server." + err.message);
  284. throw err;
  285. }
  286. });
  287. // get on /student
  288. app.get('/student', async function (req, res) {
  289. try {
  290. // prepare the select query
  291. let sql = "SELECT * FROM students;";
  292. // run query
  293. let result = await performDatabaseQuery(CONNECTION_PARAMETERS, sql);
  294. // inform the client about successful operation
  295. res.status(200).send(result);
  296. } catch (err) {
  297. // inform the client about errors
  298. res.status(500).send("Eroare server." + err.message);
  299. throw err;
  300. }
  301. });
  302. // delete on /student
  303. app.delete('/student', async function (req, res) {
  304. try {
  305. // get data from client request
  306. let id = req.body.id;
  307. // prepare the delete query
  308. let sql = "DELETE FROM students WHERE id = " + id + ";";
  309. console.log(sql);
  310. // run query
  311. await performDatabaseQuery(CONNECTION_PARAMETERS, sql);
  312. // inform the client about successful operation
  313. res.status(200).send();
  314. } catch (err) {
  315. // inform the client about errors
  316. res.status(500).send("Eroare server." + err.message);
  317. throw err;
  318. }
  319. });
  320. app.put('/student', async function (req, res) {
  321. try {
  322. // get data from client request
  323. let id = req.body.id;
  324. let nume = req.body.name;
  325. let nota = req.body.grade;
  326. // prepare the delete query
  327. let sql = "update students set name='"+nume+"', grade='"+nota+"' WHERE id = '" + id + "';";
  328. console.log(sql);
  329. // run query
  330. await performDatabaseQuery(CONNECTION_PARAMETERS, sql);
  331. // inform the client about successful operation
  332. res.status(200).send();
  333. } catch (err) {
  334. // inform the client about errors
  335. res.status(500).send("Eroare server." + err.message);
  336. throw err;
  337. }
  338. });
  339. /****************************************************************/
  340. /************* VALIDATION FUNCTIONS *****************************/
  341. /****************************************************************/
  342. // private constants for validation
  343. const NAME_MIN_LENGTH = 3;
  344. const NAME_MAX_LENGTH = 100;
  345. const GRADE_MIN_VALUE = 1;
  346. const GRADE_MAX_VALUE = 10;
  347. /**
  348. * Test the validity of a student (name and grade).
  349. * @param {object} student - The student to be validated.
  350. * @throws {error} An error resulting from validation.
  351. */
  352. function testValidity(student) {
  353. let errorMessages = "";
  354. if (typeof student.name === "undefined" || student.name === null || student.name.length < NAME_MIN_LENGTH || student.name.length > NAME_MAX_LENGTH) {
  355. errorMessages += "Name should have at least three characters and should not exceed fifty characters.";
  356. }
  357. if (typeof student.grade === "undefined" || student.grade === null || isNaN(student.grade) || student.age < GRADE_MIN_VALUE || student.grade > GRADE_MAX_VALUE) {
  358. errorMessages += "Grade should be a number between 1 and 10.";
  359. }
  360. if (errorMessages) {
  361. throw new Error(errorMessages);
  362. }
  363. }
  364.  
  365. // <li id="id">
  366. <label for="txtStudentId">What's your id?
  367. </label>
  368. <input type="text" id="txtStudentId" placeholder="your id" />
  369. </li>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement