Node MySQL Transaction encapsulation

Source: Internet
Author: User
Tags rollback

The way that the node callback function makes the database transaction seem to be not as simple as Java, PHP, the web to find some transaction processing package is not as simple as expected to write, or to encapsulate a bar.
The general idea of encapsulation is simple: the function accepts a transacted function, and the logic of how the transaction is handled is determined by the function, rather than the transaction that is encapsulated on the net is to assemble multiple preprocessed SQL and parameters. The transacted function requires that promise be returned. This allows us to determine whether the transaction is committed or rolled back through the promise.
According to the above ideas, the implementation of code:

Let MySQL = require (' mysql ') let config = require ('. /config ') Let pool = Mysql.createpool (config.database)//config.databa database configuration Let trans = (Tran) + {return new Promise                ((resolve, reject) = {//returns promise provides transaction success with failed interface Pool.getconnection (ERR, conn) + = {if (err) {                    Reject (Err)}else {conn.begintransaction (err) = {//Start transaction                        if (err) {conn.release () reject (err)}else {                            Let promise = TRAN (conn)//Call transaction function promise.then (result = = {                                    Conn.commit (err = {///Transaction function resolve commits the transaction if (ERR) {                                Reject (Err)}else {resolve (Result)    }}). catch (Err = {                        Conn.rollback (() = {//transaction function reject ROLLBACK TRANSACTION conn.release ()                Reject (Err)})})} })            }        })    })}

The transaction handler accepts the database connection object conn, where I encapsulate the database execution statement:

trans.query = (conn, sql, params) => {    return new Promise((resolve, reject) => {        conn.query(sql, params,(err, result) => {            if(err) {                reject(err)            }else {                resolve(result)            }        })    })}

The above transaction encapsulation is complete and the application is the same as normal promise use:

trans((conn) => {             return trans.query(conn, db_user.register.user, [username, password, new Date().getTime()])                     .then(result => {                             return trans.query(conn,db_user.login, [username])                     }).then(result => {                             return trans.query(conn,db_user.register.profile,[result[0].id, nickname])                        })     }).then(result=>{         console.log(‘事务提交成功’)     }).catch(err => {         console.log(‘事务提交失败’)     })

The above case is a piece of code that I intercept the project, from which the code obviously can easily encapsulate its own logic and can execute different paths of transactional processes.

Node MySQL Transaction encapsulation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.