I have a question. I am using a NodeJS app divided in three main parts
Data access object Here, I created a function that make the direct interaction with the database only in this file.
const { response } = require('express'); const db = require('../connection/db.js');
/* Export */ module.exports = { // Insert User insertUser: (parameters) => { const sqlStatement = 'INSERT INTO users SET ?'; return new Promise((resolve, reject) => { db.query(sqlStatement, parameters, (error, response) => { if (error) { return reject(error); } return resolve(response); }) }) } }
Object class
In this class I will make the validation, and create the method with arguments, then implement the data access object insertUser
.
const db = require('../dataAccessObject/dao.js');
class User { constructor (fname, lname, age, email, password, avatar, gender) { this.fname = fname; this.lname = lname; this.age = age; this.email = email; this.password = password; this.avatar = avatar; this.gender = gender; }
/* Methods */
createUser() {
db.insertUser({
'firstName' : this.fname,
'lastName' : this.lname,
'age' : this.age,
'email' : this.email,
'password' : this.password,
'userAvatar' : this.avatar,
'gender' : this.gender
})
.then(() => {
console.log(this);
return this;
})
.catch(error => {
if (error.code == 'ER_DUP_ENTRY' && error.errno === 1062) throw new Error('This email is allready in use')
else throw error;
})
}
/* Validations */
}
module.exports = User;
Controller
const newUser = new User("fname", "lname", 22, "ema2121il", "password", "avatar", "gender"); newUser.createUser(); res.send(newUser)
I need to find a way to pass the validations errors, or the duplicate error from the point 2 (Object class) to the controller.
Please how can I do this?
So, if your goal is to return data to the express controller (from the class). The best way is to utilize the Promise Library. So your createUser
function should look like this:
createUser() {
return new Promise ((resolve, reject) => {
db.insertUser({
'firstName' : this.fname,
'lastName' : this.lname,
'age' : this.age,
'email' : this.email,
'password' : this.password,
'userAvatar' : this.avatar,
'gender' : this.gender
})
.then(() => {
console.log(this);
this.runValidations()
return resolve(this);
})
.catch(error => {
if (error.code == 'ER_DUP_ENTRY' && error.errno === 1062) {
return reject('This email is already in use')
} else {
return reject();
}
})
});
}
Then to utilize it from your controller, utilize async/await to utilize the method.
//The Controller Code
app.get('/create-user', async(req, res) => {
const user = new User(req.body) // Assuming this is how you're instantiating class
try {
const newUser = await user.createUser();
console.log("User is Created");
} catch (err) {
//Your Error will be available here.
console.log("Your Error: ", err)
}
})
This should get you what you need :)