0.2.2 • Published 5 years ago

mysql2-helpers v0.2.2

Weekly downloads
13
License
ISC
Repository
-
Last release
5 years ago

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);
});