Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // @flow
- // @author tyler
- import mysql from 'mysql';
- import type {IConfigReader} from '../ConfigReader';
- export type TDataRow = *;
- export interface ITransaction {
- query (query: string): Promise<TDataRow>;
- }
- export interface IDataClient {
- /**
- * Query the data store for a specific result row
- * @param query {string}
- * @returns {Promise<TDataRow>}
- */
- query (query: string): Promise<TDataRow>;
- /**
- * Provides an interface for transactions
- * @summary Automatically commits or rollback based on
- * included promise result. E.G. transaction(t => return t.query('blah'))
- * @param fn
- * @returns {Promise<*>}
- */
- transaction (fn: (t: ITransaction) => Promise<*>): Promise<*>;
- }
- export class MySqlDataClient {
- _pool: *;
- constructor (configReader: IConfigReader) {
- const {db} = configReader.get();
- this._pool = mysql.createPool({
- connectionLimit: db.poolSize,
- host: db.host,
- port: db.port,
- database: db.database,
- password: db.password,
- user: db.user
- });
- }
- query (query: string): Promise<TDataRow> {
- return new Promise((resolve, reject) => {
- // get a connection
- this._pool.getConnection((err, connection) => {
- if (err) {
- reject(err);
- return;
- }
- connection.query(query, (err, rows) => {
- connection.release();
- if (err) {
- reject(err);
- return;
- }
- resolve(rows);
- });
- });
- });
- }
- /**
- * Provides a transaction interface
- * @param fn
- * @returns {Promise<*>}
- */
- transaction (fn: (t: ITransaction) => Promise<*>): Promise<*> {
- return new Promise((resolve, reject) => {
- // get a connection
- this._pool.getConnection((err, connection) => {
- if (err) {
- reject(err);
- return;
- }
- // begin transaction
- connection.beginTransaction(err => {
- if (err) {
- reject(err);
- return;
- }
- // create transaction interface
- const transaction: ITransaction = {
- query (query: string): Promise<TDataRow> {
- return new Promise((resolve, reject) => {
- connection.query(query, (err, rows) => {
- if (err) {
- reject(err);
- return;
- }
- resolve(rows);
- });
- });
- }
- };
- // pass interface to caller
- fn(transaction)
- .then(result => {
- // commit transaction
- connection.commit(err => {
- if (err) {
- throw err;
- }
- resolve(result);
- });
- })
- .catch(err => {
- // rollback transaction
- connection.rollback(() => {
- reject(err);
- });
- });
- });
- });
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement