type User = {
name: string
email: string
}
This is the code snippet,
import type { PoolConnection, RowDataPacket, OkPacket } from "mysql2/promise";
type dbDefaults = RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[];
type dbQuery<T> = T & dbDefaults;
type FlattenIfArray<T> = T extends (infer R)[] ? R : T;
function isFlattenArray<T>(rows: any[]): rows is T[] {
return rows.length < 1;
}
// eslint-disable-next-line consistent-return
export async function queryWrapper<T>(
{ query, values }: { query: string; values?: string[] },
conn: PoolConnection
): Promise<T | undefined> {
try {
await conn.beginTransaction();
const [rows, _] = await conn.query<dbQuery<T>>(query, values || undefined);
await conn.commit();
if (isFlattenArray<FlattenIfArray<T>>(rows)) {
return rows;
}
return rows;
} catch (error) {
await conn.rollback();
} finally {
conn.release();
}
}
The Mysql code returns only the array
There is no issue with User[]
.
However, when using User
, I want to eliminate the array structure.
So I tried using this code, but it did not produce the desired result. What steps should I take?
I have provided additional clarification.
const result = queryWrapper<User>(query, values, conn)
When utilizing
user
, the output appears as below.
[
{
name: "user-name",
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="daafa9bfa89abdb7bbb3b6f4b9b5b7">[email protected]</a>"
}
]
However, I desire it to be displayed like this.
{
name: "user-name",
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="700503150230171d11191c5e131f1d">[email protected]</a>"
}