I am currently in the process of setting up an authentication and account creation page for my website using Express and SQLite. I am facing a challenge with my function to add users, as it involves multiple callback steps interacting with the database. I would like to ensure that all these steps have completed before ending the function so that I can send data back to the front end through the express response. This data would include any potential error codes from the database (such as user already exists) and the actual user data upon successful connection.
function addUser(username,password)
{
var db = new sqlite3.Database('./database/users.db',sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error("Open error code : "+err.errno+" ; message : "+err.message);
}
});
var statement=db.prepare("INSERT into users(username,password) VALUES(?,?)")
statement.run(username,password,(err)=>{
if (err) {
console.error("Run error code : "+err.errno+" ; message : "+err.message);
}
});
statement.finalize((err)=>{
if(err)
{
console.error("Finalize error code : "+err.errno+" ; message : "+err.message);
}
})
db.close()
}
The desired server response format is as follows:
app.post('/addUser',jsonParser,(req,res)=>{
res.status(200).send(JSON.stringify({error : addUser(req.body.username,req.body.password)}))
});
The current issue revolves around ensuring that any error generated within the steps of the addUser() function are properly returned.
I attempted various methods such as declaring variables to store errors and user data but faced challenges with the asynchronous nature of callbacks.
A solution was found by incorporating promises and then() functions as illustrated below:
async function addUser(username,password)
{
// Function implementation using await and promises
}
app.post('/addUser',jsonParser,(req,res)=>{
addUser(req.body.username,req.body.password).then((value)=>{
console.log(value)
res.status(200).send(JSON.stringify(value))
})
});
Tests have shown that working with objects like data{} within the addUser() function is crucial for manipulating variables across the code effectively.