Node Mysql transaction package

way node database transaction callback function makes seemingly did not like java, php write simple as the Internet to find some transaction processing package did not meet expectations as simple as writing your own, or their packaging a bar.
Package general idea is very simple: a transaction processing function accepts a function of how transaction processing logic is determined by the function, rather than online transaction package is assembled, and a plurality of preprocessing parameter SQL. The transaction handler asked to return Promise. So that we can be determined by the Promise is to commit the transaction or roll back the transaction.
According to the idea, implementation code:

let mysql = require('mysql')
let config = require('../config')

let pool = mysql.createPool (config.database) //config.databa database configuration
the let = Trans (Tran) => {
return new new Promise ((Resolve, Reject) => {// return promise to provide transaction success interface failure
pool.getConnection ((ERR, Conn) => {
IF (ERR) {
Reject (ERR)
} the else {
conn.beginTransaction ((ERR) => {// start transaction
IF (ERR) {
conn.release ()
Reject (ERR)
} {the else
the let Promise = Tran (Conn) // calls the transaction processing function
promise.then (Result => {
conn.commit (ERR => {// transaction commit the transaction handler resolve the
IF (ERR) {
Reject (ERR)
} the else {
Resolve (Result)
}
})
}). the catch (ERR => {
conn.rollback (() => {// reject the transaction is rolled back transaction function
conn.release ()
reject (ERR)
})
})
}
})
}
})
})
}
Transaction processing function accepts a database connection object conn, here I encapsulate database executes the statement:

= trans.query (Conn, SQL, the params) => {
return new new Promise ((Resolve, Reject) => {
conn.query (SQL, the params, (ERR, Result) => {
IF (ERR) {
Reject (ERR )
} {the else
Resolve (Result)
}
})
})
}
The above transaction is completed package, the application and use the same normal Promise:

Trans ((Conn) => {
return trans.query (Conn, db_user.register.user, [username, password, new new a Date (). the getTime ()])
.then (Result => {
return trans.query (Conn, db_user.login, [username])
}). the then (Result => {
return trans.query (Conn, db_user.register.profile, [Result [0] .id, Nickname])
})
}). the then (Result = > {
console.log ( 'the transaction commits successfully')
}). the catch (ERR => {
console.log ( 'failure to submit the transaction')
})
the above case is my piece of code interception of the project, it is clear from the above code can easily package own logic, transaction flow may be performed in different paths.

Guess you like

Origin blog.51cto.com/14451335/2421065