mysql2-helpers
v0.2.2
Published
This module provides helpers for [mysql2](https://www.npmjs.com/package/mysql2) to simplify context-based transactions execution.
Downloads
4
Readme
MySQL 2 Helpers
This module provides helpers for mysql2 to simplify context-based transactions execution.
It only supports promisified versions of Connection
and Pool
;
Usage
Query
Helper that uses mysql2
query()
method.
const mysqlHelper = require('mysql2-helpers');
// connection is an instance of mysql2 connection/pool
mysqlHelper.setDefaultConnection(connection);
let sql = 'SELECT * FROM table WHERE id = ?';
let params = [id];
let transformFn = (res, info) => res.name;
mysqlHelper.query(sql, params, transformFn).then(name => console.log(name));
PreparedStatement
Helper that uses mysql2
execute()
method.
const mysqlHelper = require('mysql2-helpers');
// connection is an instance of mysql2 connection/pool
mysqlHelper.setDefaultConnection(connection);
let sql = 'SELECT * FROM table WHERE id = ?';
let params = [id];
let transformFn = (res, info) => res.name;
mysqlHelper.execute(sql, params, transformFn).then(name => console.log(name));
Transaction
Helper that allows to execute queries
and prepared statements
on the same connection inside a transaction. Every method called inside the function will run within the same transaction.
const mysqlHelper = require('mysql2-helpers');
const IsolationLevel = mysqlHelper.IsolationLevel;
// connection is an instance of mysql2 connection/pool
mysqlHelper.setDefaultConnection(connection);
let sql = 'SELECT * FROM table WHERE id = ?';
let params = [id];
let transformFn = (res, info) => res.name;
mysqlHelper.transaction(IsolationLevel.SERIALIZABLE, async () => {
const name = await mysqlHelper.execute(sql, params, transformFn);
console.log(name);
});