Refactor DB Handler. Use Bun native SQL adapter.
This commit is contained in:
+28
-33
@@ -1,11 +1,9 @@
|
||||
import type { Connection, ConnectionConfig } from "mariadb";
|
||||
import type { BUN_MARIADB_TableSchemaType, DBResponseObject } from "../types";
|
||||
import grabDBConnection from "./grab-db-connection";
|
||||
import type { DBInsertReturn, DBResponseObject } from "../types";
|
||||
import MariaDBClient from "./mariadb";
|
||||
|
||||
type Param = {
|
||||
query: string;
|
||||
values?: string[] | object;
|
||||
config?: ConnectionConfig;
|
||||
values?: any[];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -14,43 +12,40 @@ type Param = {
|
||||
*/
|
||||
export default async function dbHandler<
|
||||
T extends { [k: string]: any } = { [k: string]: any },
|
||||
>({ query, values, config }: Param): Promise<DBResponseObject> {
|
||||
let CONNECTION: Connection | undefined;
|
||||
let results: T | null = null;
|
||||
|
||||
>({ query, values }: Param): Promise<DBResponseObject> {
|
||||
try {
|
||||
CONNECTION = await grabDBConnection({ config });
|
||||
const res = await MariaDBClient.unsafe(query, values);
|
||||
|
||||
if (query && values) {
|
||||
const queryResults = await CONNECTION.query(query, values);
|
||||
results = queryResults[0];
|
||||
} else {
|
||||
const queryResults = await CONNECTION.query(query);
|
||||
results = queryResults[0];
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (
|
||||
error.message &&
|
||||
typeof error.message == "string" &&
|
||||
error.message.match(/Access denied for user.*password/i)
|
||||
) {
|
||||
throw new Error("Authentication Failed!");
|
||||
}
|
||||
const count = res.count;
|
||||
const last_insert_id = res.lastInsertRowid;
|
||||
const affected_rows = res.affectedRows;
|
||||
|
||||
results = null;
|
||||
} finally {
|
||||
await CONNECTION?.end();
|
||||
}
|
||||
const res_array = (() => {
|
||||
try {
|
||||
return JSON.parse(JSON.stringify(res)) as T[];
|
||||
} catch (error) {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
|
||||
const insert_return: DBInsertReturn = {
|
||||
count,
|
||||
last_insert_id,
|
||||
affected_rows,
|
||||
};
|
||||
|
||||
if (results) {
|
||||
return {
|
||||
success: true,
|
||||
payload: Array.isArray(results) ? results : undefined,
|
||||
single_res: Array.isArray(results) ? undefined : results,
|
||||
payload: res_array,
|
||||
single_res: res_array?.[0],
|
||||
insert_return,
|
||||
};
|
||||
} else {
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
error: "DB Handler Error => " + error.message,
|
||||
msg: "DB Handler Error => " + error.message,
|
||||
};
|
||||
} finally {
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user