works
This commit is contained in:
@ -1,8 +1,14 @@
|
||||
import mariadb from 'mariadb'
|
||||
import { stringify } from 'querystring'
|
||||
|
||||
let conn : mariadb.Connection
|
||||
|
||||
|
||||
interface Hero {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
|
||||
class DbHandle {
|
||||
private _conn? : mariadb.Connection
|
||||
|
||||
@ -17,8 +23,11 @@ class DbHandle {
|
||||
})
|
||||
}
|
||||
|
||||
public get(stmt : string) : Promise<any> {
|
||||
return this._conn?.query(stmt) ?? Promise.reject(new Error('Connection not ready 1'))
|
||||
public async getHeroes() : Promise<Hero[]> {
|
||||
const result = await this._conn?.query("SELECT id, name FROM hero") ?? Promise.reject(new Error('Connection not ready 1'))
|
||||
return result.map((row: Record<string, unknown>) => {
|
||||
return { id: row.id, name: row.name ?? 'unknown' }
|
||||
})
|
||||
}
|
||||
|
||||
public close() : Promise<void> {
|
||||
@ -43,10 +52,13 @@ dbHandle.connect()
|
||||
|
||||
async function exec() : Promise<void> {
|
||||
const dbHandle = new DbHandle()
|
||||
await dbHandle.connect()
|
||||
const result = await dbHandle.get("SELECT * FROM hero")
|
||||
console.log(result)
|
||||
await dbHandle.close()
|
||||
try {
|
||||
await dbHandle.connect()
|
||||
const heroes : Hero[] = await dbHandle.getHeroes()
|
||||
console.log(heroes)
|
||||
} finally {
|
||||
await dbHandle.close()
|
||||
}
|
||||
}
|
||||
|
||||
exec().catch((err) => console.log(err.message))
|
||||
|
Reference in New Issue
Block a user