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?
joilibrary