Advertisement
Guest User

Untitled

a guest
May 15th, 2018
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.30 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. // get on /student
  93. app.get('/student', async function (req, res) {
  94. try {
  95. // prepare the select query
  96. let sql = "SELECT * FROM students;";
  97. // run query
  98. let result = await performDatabaseQuery(CONNECTION_PARAMETERS, sql);
  99. // inform the client about successful operation
  100. res.status(200).send(result);
  101. } catch (err) {
  102. // inform the client about errors
  103. res.status(500).send("Eroare server." + err.message);
  104. throw err;
  105. }
  106. });
  107. // delete on /student
  108. app.delete('/student', async function (req, res) {
  109. try {
  110. // get data from client request
  111. let id = req.body.id;
  112. // prepare the delete query
  113. let sql = "DELETE FROM students WHERE id = " + id + ";";
  114. console.log(sql);
  115. // run query
  116. await performDatabaseQuery(CONNECTION_PARAMETERS, sql);
  117. // inform the client about successful operation
  118. res.status(200).send();
  119. } catch (err) {
  120. // inform the client about errors
  121. res.status(500).send("Eroare server." + err.message);
  122. throw err;
  123. }
  124. });
  125. app.put('/student', async function (req, res) {
  126. try {
  127. // get data from client request
  128. let student = {
  129. name: req.body.name,
  130. grade: req.body.grade,
  131. id:req.body.id
  132. };
  133. // data must be validated on the server
  134. testValidity(student);
  135. // prepare the insert query
  136. let sql = "UPDATE students SET name='"+ student.name+ "',grade='"+student.grade+"' WHERE id='"+student.id+"';";
  137. // run query
  138. await performDatabaseQuery(CONNECTION_PARAMETERS, sql);
  139. // inform the client about successful operation
  140. res.status(200).send();
  141. } catch (err) {
  142. // inform the client about errors
  143. res.status(500).send("Eroare server." + err.message);
  144. throw err;
  145. }
  146. });
  147. /****************************************************************/
  148. /************* VALIDATION FUNCTIONS *****************************/
  149. /****************************************************************/
  150. // private constants for validation
  151. const NAME_MIN_LENGTH = 3;
  152. const NAME_MAX_LENGTH = 100;
  153. const GRADE_MIN_VALUE = 1;
  154. const GRADE_MAX_VALUE = 10;
  155. /**
  156. * Test the validity of a student (name and grade).
  157. * @param {object} student - The student to be validated.
  158. * @throws {error} An error resulting from validation.
  159. */
  160. function testValidity(student) {
  161. let errorMessages = "";
  162. if (typeof student.name === "undefined" || student.name === null || student.name.length < NAME_MIN_LENGTH || student.name.length > NAME_MAX_LENGTH) {
  163. errorMessages += "Name should have at least three characters and should not exceed fifty characters.";
  164. }
  165. if (typeof student.grade === "undefined" || student.grade === null || isNaN(student.grade) || student.age < GRADE_MIN_VALUE || student.grade > GRADE_MAX_VALUE) {
  166. errorMessages += "Grade should be a number between 1 and 10.";
  167. }
  168. if (errorMessages) {
  169. throw new Error(errorMessages);
  170. }
  171. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement