Ad
How To Correctly Execute This Promise Based SQL Query?
I'm using MySQL2 to connect my Node.js app with a MySQL Database. Unfortunately trying to perform some promise based prepared statements I just can't get a proper function setup that either returns successfully after entering the record or to throw an error whenever something goes wrong.
Any ideas on how to fix the code below?
// Connection Settings
const connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
port: process.env.DB_PORT
})
// Promise based SQL Prepared Statement
db.pps = ({ query, variables, error }) => {
return new Promise((resolve, reject) => {
connection.execute(query, variables, (err, results) => {
if (err) {
console.log(`Error: ${error} \n ${err.sqlMessage}`)
return reject(err)
}
return resolve(results)
})
})
}
// Sign Up
auth.signup = (req, res) => {
const query = `
INSERT INTO User (Id, Email, Password)
VALUES (UUID_TO_BIN(UUID()), ?, ?)
`
const variables = [req.query.email, req.query.password]
db.promise({ query, variables }, (err, result) => {
if (err) {
res.status(400)
}
res.status(200)
})
}
Ad
Answer
you can use the prepared statement query function like below.
If you are not using this inside a function
auth.signup = (req, res) => {
const query = `
INSERT INTO User (Id, Email, Password)
VALUES (UUID_TO_BIN(UUID()), ?, ?)
`
const variables = [req.query.email, req.query.password]
db.pps({ query, variables })
.then(result => {
res.status(200)
})
.catch( error => {
res.status(400)
});
}
Or use async await
auth.signup = async (req, res) => {
const query = `
INSERT INTO User (Id, Email, Password)
VALUES (UUID_TO_BIN(UUID()), ?, ?)
`
const variables = [req.query.email, req.query.password]
try {
await db.pps({ query, variables });
res.status(200)
} catch (err) {
res.status(400)
}
}
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad