Я новичок в том, как использовать mysql с nodejs
, поэтому я попробовал этот урок по основам c на YouTube и начал его настраивать
Я пытаюсь используйте async / await, чтобы я мог начать транзакцию в mysql
, вот код
const pool = require('../../config/database')
module.exports = {
create: async (data, callBack) => {
const connection = await pool.getConnection();
await connection.beginTransaction();
try {
await connection.query(
`insert into user_details(fullname,gender,email,password,phone_number)
values(?,?,?,?,?)`,
[
data.fullName,
data.gender,
data.email,
data.password,
data.phone_number
],
(error, results, fields) =>{
if(error){
return callBack(error);
}
return callBack(null, results);
}
);
await connection.commit();
} finally {
connection.release();
}
}
}
, но соединение не определено
Я утешил пул перед строкой const connection = await pool.getConnection();
, и он не нулевой. но после const connection = await pool.getConnection();
соединение не определено
любая помощь? : D
edit: To @Terry Lennox
вот журнал
addUserDetails, creating connection...
addUserDetails, creating connection...
addUserDetails, starting transaction...
addUserDetails, running query...
addUserDetails, an error occurred: TypeError: Cannot read property 'fullName' of undefined
at Object.addUserDetails [as create] (C:\Playground\nodejs-mysql\api\users\user.service.js:19:26)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:12412) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'fullName' of undefined
at Object.addUserDetails [as create] (C:\Playground\nodejs-mysql\api\users\user.service.js:19:26)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:12412) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12412) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
addUserDetails, starting transaction...
addUserDetails, running query...
addUserDetails, committing transaction...
addUserDetails, transaction committed.
Edit:
Вот мое приложение. js
require('dotenv').config();
const express = require('express');
const app = express();
const userRouter = require('./api/users/user.router');
app.use(express.json());
app.use('/api/users', userRouter);
app.listen(process.env.PORT, ()=>{
console.log("Server is now running");
})
вот мой user.router. js
const userController = require('./user.controller')
const router = require('express').Router();
const {checkToken} = require('../../auth/token.validation');
router.post("/", userController.createUser);
router.get("/", checkToken, userController.getUsers);
router.get("/:id", checkToken, userController.getUserById);
router.patch("/", checkToken, userController.updateUser);
router.delete("/:id", checkToken, userController.deleteUser);
router.post("/login", userController.login)
module.exports = router;
вот мой контроллер
const userService = require('./user.service');
const { genSaltSync, hashSync, compareSync} = require('bcryptjs');
const { sign } = require('jsonwebtoken');
module.exports = {
createUser: (req,res) =>{
const body = req.body;
const salt = genSaltSync(10);
body.password = hashSync(body.password, salt);
userService.create()
userService.create(body, (err, results)=>{
if(err){
console.log(err);
return res.status(500).json({
success: 0,
message: "An error occured: "+ err
})
}
return res.status(200).json({
success: 1,
code: results,
data: body
});
})
}
}
и, наконец, мой сервис. js
async function addUserDetails(data) {
console.log("addUserDetails, creating connection...");
const connection = await pool.getConnection();
try {
console.log("addUserDetails, starting transaction...");
await connection.beginTransaction();
console.log("addUserDetails, running query...");
const queryResult = await connection.query(
`insert into user_details(fullname,gender,email,password,phone_number) values(?,?,?,?,?)`,
[
data.fullName,
data.gender,
data.email,
data.password,
data.phone_number
]
);
console.log("addUserDetails, committing transaction...");
await connection.commit();
console.log("addUserDetails, transaction committed.");
return queryResult;
} catch (error) {
console.error("addUserDetails, an error occurred:", error);
} finally {
connection.release();
}
}
module.exports = {
create: addUserDetails
}
также вот мой конфиг для пула
PORT = 3000
DB_PORT = 3306
DB_HOST = localhost
DB_USER = root
DB_PASS =