begin transaction in node js using pool query

Solutions on MaxInterview for begin transaction in node js using pool query by the best coders in the world

showing results for - "begin transaction in node js using pool query"
Émilien
20 Jan 2017
1module.exports = {
2  creatUser: (req) => {
3    return new Promise((resolve, reject) => {
4      pool.getConnection(function (err, connection) {
5        connection.beginTransaction(function (err) {
6          if (err) {
7            //Transaction Error (Rollback and release connection)
8            connection.rollback(function () {
9              connection.release();
10            });
11
12            return reject(err);
13          } else {
14            connection.query(
15              `insert into ?? (name, email) values (?,?)`,
16              [
17                "user",
18                req.name.trim(),
19                req.email.trim()
20              ],
21
22              function (err, uResults) {
23                if (err) {
24                  //Query Error (Rollback and release connection)
25                  connection.rollback(function () {
26                    connection.release();
27                  });
28                  return reject(err);
29                } else {
30                  let values = [];
31                  req.departmentId.forEach(function (result) {
32                    let l = [uResults.insertId, result];
33                    values.push(l);
34                  });
35                  console.log("vale", values);
36                  connection.query(
37                    `insert into u_dep (u_id, dep_id) values ?`,
38                    [values],
39                    function (err, results) {
40                      if (err) {
41                         connection.rollback(function () {
42                          connection.release();
43                        });
44                        return reject(err);
45                      } else {
46                        connection.commit(function (err) {
47                          if (err) {
48                            connection.rollback(function () {
49                              connection.release();
50                            });
51                            return reject(err);
52                          } else {
53                            connection.release();
54                            return resolve(uResults);
55                          }
56                        });
57                      }
58                    }
59                  );
60                }
61              }
62            );
63          }
64        });
65      });
66    });
67  },
68};