mirror of
https://github.com/darksaid98/oxmysql.git
synced 2026-12-01 14:38:50 +00:00
refactor(db/startTransaction): add 30s timeout to transactions
This commit is contained in:
1 parent
6a014b51e2
commit
20083c6831
1 file changed
+22
-7
@@ -2,6 +2,19 @@ import { getPoolConnection } from './connection';
|
||||
import { logError } from '../logger';
|
||||
import { CFXCallback, CFXParameters } from '../types';
|
||||
import { parseArguments } from 'utils/parseArguments';
|
||||
import { PoolConnection } from 'mysql2/promise';
|
||||
|
||||
async function runQuery(conn: PoolConnection | null, sql: string, values: CFXParameters) {
|
||||
[sql, values] = parseArguments(sql, values);
|
||||
|
||||
if (!conn)
|
||||
throw new Error(
|
||||
`Query: ${sql}\n${JSON.stringify(values)}\nConnection used by transaction timed out after 30 seconds.`
|
||||
);
|
||||
|
||||
const [rows] = await conn.query(sql, values);
|
||||
return rows;
|
||||
}
|
||||
|
||||
export const startTransaction = async (
|
||||
invokingResource: string,
|
||||
@@ -9,20 +22,21 @@ export const startTransaction = async (
|
||||
cb?: CFXCallback,
|
||||
isPromise?: boolean
|
||||
) => {
|
||||
const conn = await getPoolConnection();
|
||||
let conn: PoolConnection | null = await getPoolConnection();
|
||||
let response: boolean | null = false;
|
||||
|
||||
if (!conn) return;
|
||||
|
||||
let response = false;
|
||||
setTimeout(() => (response = null), 30000);
|
||||
|
||||
try {
|
||||
await conn.beginTransaction();
|
||||
|
||||
const commit = await queries(async (sql: string, values: CFXParameters) => {
|
||||
[sql, values] = parseArguments(sql, values);
|
||||
const [rows] = await conn.query(sql, values);
|
||||
return rows;
|
||||
});
|
||||
const commit = await queries((sql: string, values: CFXParameters) =>
|
||||
runQuery(response === null ? null : conn, sql, values)
|
||||
);
|
||||
|
||||
if (response === null) throw new Error(`Transaction has timed out after 30 seconds.`);
|
||||
|
||||
response = commit === false ? false : true;
|
||||
response ? conn.commit() : conn.rollback();
|
||||
@@ -31,6 +45,7 @@ export const startTransaction = async (
|
||||
logError(invokingResource, cb, isPromise, err);
|
||||
} finally {
|
||||
conn.release();
|
||||
conn = null;
|
||||
}
|
||||
|
||||
return cb ? cb(response) : response;
|
||||
|
||||
Reference in new issue
Block a user