From e2bcaf66c8b44c773e09e23a60b09669c2bcadd3 Mon Sep 17 00:00:00 2001
From: xfarrow <ale99napoli@icloud.com>
Date: Thu, 5 Oct 2023 12:20:00 +0200
Subject: [PATCH] Update

---
 backend/api.js                 | 57 ++++++++++++++++++++++++++++++++--
 backend/tutorials/callbacks.js | 44 ++++++++++++++++++++++++++
 backend/tutorials/delay.js     | 12 +++++++
 backend/tutorials/promises.js  | 46 +++++++++++++++++++++++++++
 4 files changed, 157 insertions(+), 2 deletions(-)
 create mode 100644 backend/tutorials/callbacks.js
 create mode 100644 backend/tutorials/delay.js
 create mode 100644 backend/tutorials/promises.js

diff --git a/backend/api.js b/backend/api.js
index 0233928..b33c248 100644
--- a/backend/api.js
+++ b/backend/api.js
@@ -35,6 +35,10 @@ app.get('/api/items', (req, res) => {
 });
 
 // POST - Register an account
+
+// (req, res) => { ... } is a callback which usually indicates that the
+// execution of the code contained between brackets will continue
+// asynchronously.
 app.post('/api/register', (req, res) => {
   const userData = req.body;
   
@@ -43,8 +47,8 @@ app.post('/api/register', (req, res) => {
     return res.status(400).json("Invalid request");
   }
 
-  // The callback denoted by the arrow function is executed asynchronously
-  // from the rest of the code outside of the hash() function
+  // The callback denoted by the arrow function is executed
+  // when hash() has finished its execution.
   bcrypt.hash(userData.password, 10, (err, hashedPassword) => {
     
     if (err) {
@@ -95,6 +99,55 @@ app.post('/api/register', (req, res) => {
   });
 });
 
+app.post('/api/registerv2', (req, res) => {
+  const userData = req.body;
+  
+  // Ensure that the required fields are present before proceeding
+  if (!userData.display_name || !userData.email || !userData.password) {
+    return res.status(400).json("Invalid request");
+  }
+
+  bcrypt.hash(userData.password, 10)
+    .then( hashedPassword => {
+      // Generate activation link token
+      const activationLink = crypto.randomBytes(16).toString('hex');
+          // Acquire a connection from the pool
+          pool.connect()
+          .then(async (client) => {
+            // SQL query with placeholders for parameters
+            const insertQuery = `
+            INSERT INTO "User" (display_name, date_of_birth, place_of_living, is_looking_for_job, email, password)
+            VALUES ($1, $2, $3, $4, $5, $6)
+            RETURNING *`; // Return the inserted row
+      
+          try {
+              try {
+                const result = await client.query(insertQuery, [
+                  userData.display_name,
+                  userData.date_of_birth,
+                  userData.place_of_living,
+                  userData.is_looking_for_job,
+                  userData.email,
+                  hashedPassword
+                ]);
+                // Respond with the inserted user data
+                res.status(200).json(result.rows[0]);
+              } catch (error) {
+                console.error('Error inserting data:', error);
+                res.status(500).json("Internal server error");
+              }
+            } finally {
+              // Release the connection back to the pool
+              client.release();
+            }
+        })
+        .catch((error) => {
+          console.error('Error acquiring a connection from the pool:', error);
+          res.status(500).json("Internal server error");
+        });
+    });
+});
+
 // Start the server
 app.listen(port, () => {
   console.log(`Blink API server is running on port ${port}`);
diff --git a/backend/tutorials/callbacks.js b/backend/tutorials/callbacks.js
new file mode 100644
index 0000000..c430ade
--- /dev/null
+++ b/backend/tutorials/callbacks.js
@@ -0,0 +1,44 @@
+// https://javascript.info/callbacks
+
+ function execute_action(param, callback){
+
+    if(param == "something"){
+        console.log("Executing action: " + param);
+        callback(null, Date.now());
+    }
+    else{
+        // We can call callback with one argument even if
+        // the signature states two parameters
+        callback(new Error("Invalid parameter"))
+    }
+}
+
+function entryPoint(){
+    /* ===== Begin Simple callback ===== */
+
+    execute_action("something", function (error, time_of_completion){
+        if(error){
+            console.log("Something happened");
+        }
+        else{
+            console.log("Time of completion: " + new Date(time_of_completion).toDateString());
+        }
+    });
+    console.log("I started here!");
+    /*
+    Ciò è utile se ad esempio execute_action fa operazioni lente (ad esempio 
+    scrittura su database, connessioni HTTP ecc..) ma abbiamo bisogno
+    del suo valore di ritorno per continuare una determinata operazione
+    (in questo caso la data di completamento dell'esecuzione), 
+    senza però bloccare le altre operazioni che non hanno bisogno di tale
+    valore, in questo caso console.log("I started here!");
+
+    Questo però è solo un esempio in quanto le istruzioni verranno
+    eseguite in maniera sincrona (non concorrenti), ma che ci permette di
+    comprendere le basi di questo meccanismo.
+    */
+    
+    /* ===== End Simple Callback ===== */
+}
+
+entryPoint();
\ No newline at end of file
diff --git a/backend/tutorials/delay.js b/backend/tutorials/delay.js
new file mode 100644
index 0000000..6b07f86
--- /dev/null
+++ b/backend/tutorials/delay.js
@@ -0,0 +1,12 @@
+/*
+    The built-in function setTimeout uses callbacks. Create a promise-based alternative.
+    The function delay(ms) should return a promise. That promise should resolve after ms milliseconds, so that we can add .then to it, like this:
+*/
+
+function delay(ms){
+    return new Promise(resolve => {
+        setTimeout(resolve, ms);
+    });
+}
+
+delay(1000).then(() => console.log("Hello world!"));
diff --git a/backend/tutorials/promises.js b/backend/tutorials/promises.js
new file mode 100644
index 0000000..8e571c5
--- /dev/null
+++ b/backend/tutorials/promises.js
@@ -0,0 +1,46 @@
+// https://javascript.info/promise-basics
+
+/*
+    The function passed to Promise is called "executor". When Promise gets
+    created, the executor gets executed.
+    When the Promise ends, it should either call the "resolve" or "reject"
+    callbacks:
+    resolve(value) — if the job is finished successfully, with result value.
+    reject(error) — if an error has occurred, error is the error object.
+*/
+let promise = new Promise(function(resolve, reject) {
+    setTimeout(() => resolve("done"), 500);
+  });
+
+/*
+    The first argument of .then is a function that runs when the promise is resolved and receives the result.
+    The second argument of .then is a function that runs when the promise is rejected and receives the error.
+*/
+promise.then(
+    result => console.log("The operation was successful. It returned " + result),
+    error => console.log("The operation was not successful: " + error)
+);
+
+/*
+    Or we can pass only one argument if we're interested only in a positive result
+*/
+promise.then(
+    result => console.log("The operation was successful. It returned " + result)
+);
+
+/*
+    Or we can pass only one argument to the method "catch" if we're interested
+    in negative results only.
+
+    promise.catch internally just calls promise.then(null, f)
+*/
+promise.catch(
+    error => console.log(error)
+);
+
+/*
+    finally gets always called
+*/
+promise.finally(
+    () => console.log("The execution has terminated. Bye")
+);
\ No newline at end of file