mirror of
https://github.com/xfarrow/blink
synced 2025-06-27 09:03:02 +02:00
update
This commit is contained in:
143
backend/api.js
143
backend/api.js
@ -1,143 +0,0 @@
|
||||
/*
|
||||
** This code is part of Blink
|
||||
** licensed under GPLv3
|
||||
*/
|
||||
|
||||
// require() always returns a function
|
||||
const express = require('express');
|
||||
const bcrypt = require('bcrypt');
|
||||
const { Pool } = require('pg');
|
||||
const crypto = require('crypto');
|
||||
|
||||
// We can do express() because the express
|
||||
// module exports a function. Exporting a function
|
||||
// means making a JavaScript function defined in one
|
||||
// module available for use in another module.
|
||||
const app = express();
|
||||
const port = 3000;
|
||||
|
||||
// Middleware which parses JSON for POST requests
|
||||
app.use(express.json());
|
||||
|
||||
const pool = new Pool({
|
||||
user: 'postgres',
|
||||
host: 'localhost',
|
||||
database: 'Blink',
|
||||
password: 'postgres',
|
||||
port: 5432,
|
||||
max: 10,
|
||||
idleTimeoutMillis: 30000,
|
||||
});
|
||||
|
||||
// Define a route to get all items
|
||||
app.get('/api/items', (req, res) => {
|
||||
res.json(items);
|
||||
});
|
||||
|
||||
// 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;
|
||||
|
||||
// Ensure that the required fields are present before proceeding
|
||||
if (!userData.display_name || !userData.email || !userData.password) {
|
||||
return res.status(400).json("Invalid request");
|
||||
}
|
||||
|
||||
// The callback denoted by the arrow function is executed
|
||||
// when hash() has finished its execution.
|
||||
bcrypt.hash(userData.password, 10, (err, hashedPassword) => {
|
||||
|
||||
if (err) {
|
||||
console.error('Error hashing password:', err);
|
||||
}
|
||||
|
||||
else {
|
||||
|
||||
// Generate activation link token
|
||||
const activationLink = crypto.randomBytes(16).toString('hex');
|
||||
|
||||
// Acquire a connection from the pool
|
||||
pool.connect()
|
||||
.then((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
|
||||
|
||||
return client.query(insertQuery, [
|
||||
userData.display_name,
|
||||
userData.date_of_birth,
|
||||
userData.place_of_living,
|
||||
userData.is_looking_for_job,
|
||||
userData.email,
|
||||
hashedPassword
|
||||
])
|
||||
.then((result) => {
|
||||
// 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");
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
app.post('/api/registerv2', async (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");
|
||||
}
|
||||
|
||||
const hashPasswordPromise = bcrypt.hash(userData.password, 10);
|
||||
var client;
|
||||
try{
|
||||
client = await pool.connect();
|
||||
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 *`;
|
||||
const result = await client.query(insertQuery, [
|
||||
userData.display_name,
|
||||
userData.date_of_birth,
|
||||
userData.place_of_living,
|
||||
userData.is_looking_for_job,
|
||||
userData.email,
|
||||
await hashPasswordPromise
|
||||
]);
|
||||
res.status(200).json(result.rows[0]);
|
||||
}
|
||||
catch (error){
|
||||
console.error('Error inserting data:', error);
|
||||
res.status(500).json("Internal server error");
|
||||
}
|
||||
finally {
|
||||
if (client) {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// Start the server
|
||||
app.listen(port, () => {
|
||||
console.log(`Blink API server is running on port ${port}`);
|
||||
});
|
26
backend/apis/nodejs/api.js
Normal file
26
backend/apis/nodejs/api.js
Normal file
@ -0,0 +1,26 @@
|
||||
/*
|
||||
** This code is part of Blink
|
||||
** licensed under GPLv3
|
||||
*/
|
||||
|
||||
// require() always returns a function
|
||||
const express = require('express');
|
||||
const api_controller = require('./api_controller.js');
|
||||
|
||||
// We can do express() because the express
|
||||
// module exports a function. Exporting a function
|
||||
// means making a JavaScript function defined in one
|
||||
// module available for use in another module.
|
||||
const app = express();
|
||||
const port = 3000;
|
||||
|
||||
// Middleware which parses JSON for POST requests
|
||||
app.use(express.json());
|
||||
|
||||
app.post('/blinkapi/register', api_controller.register_async);
|
||||
app.post('blinkapi/login', api_controller.login);
|
||||
|
||||
// Start the server
|
||||
app.listen(port, () => {
|
||||
console.log(`Blink API server is running on port ${port}`);
|
||||
});
|
121
backend/apis/nodejs/api_controller.js
Normal file
121
backend/apis/nodejs/api_controller.js
Normal file
@ -0,0 +1,121 @@
|
||||
const bcrypt = require('bcrypt');
|
||||
const { Pool } = require('pg');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const pool = new Pool({
|
||||
user: 'postgres',
|
||||
host: 'localhost',
|
||||
database: 'Blink',
|
||||
password: 'postgres',
|
||||
port: 5432,
|
||||
max: 10,
|
||||
idleTimeoutMillis: 30000,
|
||||
});
|
||||
|
||||
function register(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");
|
||||
}
|
||||
|
||||
// The callback denoted by the arrow function is executed
|
||||
// when hash() has finished its execution.
|
||||
bcrypt.hash(userData.password, 10, (err, hashedPassword) => {
|
||||
|
||||
if (err) {
|
||||
console.error('Error hashing password:', err);
|
||||
}
|
||||
|
||||
else {
|
||||
|
||||
// Generate activation link token
|
||||
const activationLink = crypto.randomBytes(16).toString('hex');
|
||||
|
||||
// Acquire a connection from the pool
|
||||
pool.connect()
|
||||
.then((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
|
||||
|
||||
return client.query(insertQuery, [
|
||||
userData.display_name,
|
||||
userData.date_of_birth,
|
||||
userData.place_of_living,
|
||||
userData.is_looking_for_job,
|
||||
userData.email,
|
||||
hashedPassword
|
||||
])
|
||||
.then((result) => {
|
||||
// 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");
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function register_async(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");
|
||||
}
|
||||
|
||||
// Generate activation link token
|
||||
const activationLink = crypto.randomBytes(16).toString('hex');
|
||||
|
||||
const hashPasswordPromise = bcrypt.hash(userData.password, 10);
|
||||
var client;
|
||||
try{
|
||||
client = await pool.connect();
|
||||
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 *`;
|
||||
const result = await client.query(insertQuery, [
|
||||
userData.display_name,
|
||||
userData.date_of_birth,
|
||||
userData.place_of_living,
|
||||
userData.is_looking_for_job,
|
||||
userData.email,
|
||||
await hashPasswordPromise
|
||||
]);
|
||||
res.status(200).json(result.rows[0]);
|
||||
}
|
||||
catch (error){
|
||||
console.error('Error inserting data:', error);
|
||||
res.status(500).json("Internal server error");
|
||||
}
|
||||
finally {
|
||||
if (client) {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function login(req, res){
|
||||
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
register_async,
|
||||
login
|
||||
};
|
@ -1,44 +0,0 @@
|
||||
// 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, ma che ci permette di
|
||||
comprendere le basi di questo meccanismo.
|
||||
*/
|
||||
|
||||
/* ===== End Simple Callback ===== */
|
||||
}
|
||||
|
||||
entryPoint();
|
@ -1,46 +0,0 @@
|
||||
// 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")
|
||||
);
|
@ -1,56 +0,0 @@
|
||||
// https://javascript.info/promise-chaining
|
||||
|
||||
// .then() returns a new Promise when you do "return",
|
||||
// internally calling resolve().
|
||||
|
||||
new Promise(function(resolve, reject) {
|
||||
|
||||
setTimeout(() => resolve(1), 1);
|
||||
|
||||
}).then(function(result) {
|
||||
|
||||
console.log(result);
|
||||
return result * 2;
|
||||
|
||||
}).then(function(result) {
|
||||
|
||||
console.log(result);
|
||||
return result * 2;
|
||||
|
||||
}).then(function(result) {
|
||||
|
||||
console.log(result);
|
||||
return result * 2;
|
||||
|
||||
});
|
||||
|
||||
/*
|
||||
It will print
|
||||
1
|
||||
2
|
||||
4
|
||||
*/
|
||||
|
||||
/*
|
||||
It means that "then" is internally implemented roughly as follows:
|
||||
|
||||
function then(f){
|
||||
return new Promise(function(resolve, reject) {
|
||||
resolve(f());
|
||||
})
|
||||
}
|
||||
*/
|
||||
|
||||
// Another example:
|
||||
|
||||
fetch('http://www.fsf.org')
|
||||
// .then below runs when the remote server responds
|
||||
.then(function(response) {
|
||||
// response.text() returns a new promise that resolves with the full response text
|
||||
// when it loads
|
||||
return response.text();
|
||||
})
|
||||
.then(function(text) {
|
||||
// ...and here's the content of the remote file
|
||||
console.log(text);
|
||||
});
|
@ -1,64 +0,0 @@
|
||||
// https://javascript.info/async-await
|
||||
|
||||
// A async function always returns a promise. Other values are wrapped in a resolved promise automatically.
|
||||
// Async e Await sono solo "sintassi zuccherina" per rendere l'utilizzo delle Promise più semplice
|
||||
|
||||
async function f1() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
f1().then(console.log); // 1
|
||||
|
||||
// The keyword await makes JavaScript wait until that promise settles and returns its result.
|
||||
// It can be used in async functions only
|
||||
// Let’s emphasize: await literally suspends the function execution until the promise settles,
|
||||
// and then resumes it with the promise result.
|
||||
async function f2() {
|
||||
|
||||
let promise = new Promise((resolve, reject) => {
|
||||
setTimeout(() => resolve("done!"), 1000)
|
||||
});
|
||||
|
||||
let result = await promise; // wait until the promise resolves (*)
|
||||
|
||||
console.log(result); // "done!"
|
||||
}
|
||||
|
||||
f2();
|
||||
|
||||
// Tutto il codice nella stessa funzione (o nello stesso blocco di codice)
|
||||
// dopo "await" è da considerarsi nel "then()" di una promessa. Pertanto dopo
|
||||
// await, il flusso di esecuzione va fuori a quel blocco di codice. Ad esempio considera
|
||||
// il seguente esempio:
|
||||
async function exampleAsyncFunction() {
|
||||
console.log('Before await');
|
||||
await new Promise(function(resolve, reject) {
|
||||
setTimeout(() => resolve("done"), 500);
|
||||
}); // Pauses execution here until the promise resolves.
|
||||
console.log('After await');
|
||||
}
|
||||
|
||||
console.log('Start');
|
||||
exampleAsyncFunction();
|
||||
console.log('End');
|
||||
|
||||
// Il risultato sarà:
|
||||
// Start, Before Await, End, After await
|
||||
// Viene prima "End" e poi "After Await", perché
|
||||
// dopo await, il flusso di esecuzione ritorna al
|
||||
// chiamante
|
||||
|
||||
// Domande
|
||||
//
|
||||
// Why await only works in async function in javascript?
|
||||
// https://stackoverflow.com/questions/49640647/why-await-only-works-in-async-function-in-javascript
|
||||
//
|
||||
// Why using async-await
|
||||
// https://stackoverflow.com/questions/42624647/why-use-async-when-i-have-to-use-await
|
||||
//
|
||||
// Si faccia presente che non è possibile creare da zero una funzione asincrona (come
|
||||
// setInterval o fetch)
|
||||
// https://stackoverflow.com/questions/61857274/how-to-create-custom-asynchronous-function-in-javascript
|
||||
//
|
||||
// Altra domanda interessante
|
||||
// https://stackoverflow.com/questions/42624647/why-use-async-when-i-have-to-use-await
|
@ -1,12 +0,0 @@
|
||||
/*
|
||||
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!"));
|
@ -1,32 +0,0 @@
|
||||
Link utili:
|
||||
https://stackoverflow.com/questions/748175/asynchronous-vs-synchronous-execution-what-is-the-difference
|
||||
https://stackoverflow.com/questions/7131991/asynchronous-and-synchronous-terms
|
||||
|
||||
La parola "sincrono" in contesto informatico vuol dire "sincronizzato", ovvero
|
||||
il chiamante deve aspettare la risposta del chiamato, mentre
|
||||
"async" vuol dire "non sincronizzato".
|
||||
Ciò vuol dire (non)/sincronizzato con altre porzioni di codice.
|
||||
La definizione da dizionario invece differisce.
|
||||
Per Treccani: "Sincrono: Che avviene nello stesso momento",
|
||||
mentre sappiamo che un'operazione sincrona rispetto ad un'altra
|
||||
non avviene allo stesso tempo.
|
||||
In informatica dire "un metodo è (a)sincrono" deve
|
||||
sempre accompagnate da "rispetto a chi" è (a)sincrono.
|
||||
|
||||
Possiamo anche pensarla così: (https://stackoverflow.com/a/32052611/18371893)
|
||||
|
||||
In a nutshell, synchronization refers to two or more processes' start and end points, NOT their executions.
|
||||
In this example, Process A's endpoint is synchronized with Process B's start point:
|
||||
|
||||
SYNCHRONOUS
|
||||
|--------A--------|
|
||||
|--------B--------|
|
||||
|
||||
Asynchronous processes, on the other hand, do not have their start and endpoints synchronized:
|
||||
|
||||
ASYNCHRONOUS
|
||||
|--------A--------|
|
||||
|--------B--------|
|
||||
|
||||
Where Process A overlaps Process B, they're running concurrently or synchronously (dictionary definition), hence the confusion.
|
||||
|
Reference in New Issue
Block a user