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;
- }
- });
- // 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;
- }
- });
- 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;
- }
- });
- /****************************************************************/
- /************* 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);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement