Refactor code structure for improved readability and maintainability
This commit is contained in:
1 parent
bfce688f6a
commit
4d8b07fc68
22 files changed
+2670
-96
No files matched your search
+29
-10
@@ -1,4 +1,4 @@
|
||||
import mysql from "mysql2/promise";
|
||||
import mysql from "mysql2/promise";
|
||||
import { config } from "./config.js";
|
||||
|
||||
function createPool(password) {
|
||||
@@ -24,7 +24,15 @@ function isAccessDenied(error) {
|
||||
return error?.code === "ER_ACCESS_DENIED_ERROR";
|
||||
}
|
||||
|
||||
async function query(sql, values) {
|
||||
function isTransientConnectionError(error) {
|
||||
return ["ECONNREFUSED", "ECONNRESET", "ETIMEDOUT", "PROTOCOL_CONNECTION_LOST"].includes(error?.code);
|
||||
}
|
||||
|
||||
function delay(milliseconds) {
|
||||
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
||||
}
|
||||
|
||||
async function queryWithCredentials(sql, values) {
|
||||
try {
|
||||
return await activePool.query(sql, values);
|
||||
} catch (error) {
|
||||
@@ -33,21 +41,18 @@ async function query(sql, values) {
|
||||
}
|
||||
|
||||
for (const password of candidatePasswords) {
|
||||
if (password === activePassword) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (password === activePassword) continue;
|
||||
const fallbackPool = createPool(password);
|
||||
try {
|
||||
const result = await fallbackPool.query(sql, values);
|
||||
const previousPool = activePool;
|
||||
activePool = fallbackPool;
|
||||
activePassword = password;
|
||||
previousPool.end().catch(() => undefined);
|
||||
return result;
|
||||
} catch (fallbackError) {
|
||||
await fallbackPool.end().catch(() => undefined);
|
||||
if (!isAccessDenied(fallbackError)) {
|
||||
throw fallbackError;
|
||||
}
|
||||
if (!isAccessDenied(fallbackError)) throw fallbackError;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,4 +60,18 @@ async function query(sql, values) {
|
||||
}
|
||||
}
|
||||
|
||||
export const pool = { query };
|
||||
async function query(sql, values) {
|
||||
let lastError;
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||
try {
|
||||
return await queryWithCredentials(sql, values);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (!isTransientConnectionError(error) || attempt === 4) throw error;
|
||||
await delay(250 * 2 ** attempt);
|
||||
}
|
||||
}
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
export const pool = { query };
|
||||
Reference in new issue
Block a user