Advertisement
Guest User

Untitled

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