75 lines
1.7 KiB
TypeScript
75 lines
1.7 KiB
TypeScript
import mariadb from 'mariadb'
|
|
import { stringify } from 'querystring'
|
|
|
|
let conn : mariadb.Connection
|
|
|
|
|
|
interface Hero {
|
|
id: number
|
|
name: string
|
|
}
|
|
|
|
class DbHandle {
|
|
private _conn? : mariadb.Connection
|
|
|
|
public constructor() {}
|
|
|
|
public async connect() : Promise<void> {
|
|
this._conn = await mariadb.createConnection({
|
|
host: '172.16.10.18',
|
|
user: 'heroes',
|
|
password: 'test123',
|
|
database: 'heroes'
|
|
})
|
|
}
|
|
|
|
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> {
|
|
return this._conn?.end() ?? Promise.reject(new Error('Connection not ready 2'))
|
|
}
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
const dbHandle = new DbHandle()
|
|
dbHandle.connect()
|
|
.then(() => dbHandle.get("SELECT * FROM hero"))
|
|
.then((result) => {
|
|
console.log(result)
|
|
return dbHandle.close()
|
|
})
|
|
.catch((err) => {
|
|
console.log(err)
|
|
})
|
|
*/
|
|
|
|
async function exec() : Promise<void> {
|
|
const dbHandle = new DbHandle()
|
|
try {
|
|
await dbHandle.connect()
|
|
const heroes : Hero[] = await dbHandle.getHeroes()
|
|
console.log(heroes)
|
|
} finally {
|
|
await dbHandle.close()
|
|
}
|
|
}
|
|
|
|
exec().catch((err) => console.log(err.message))
|
|
|
|
/*
|
|
dbHandle.get("SELECT * FROM hero")
|
|
.then((result) => {
|
|
console.log(result)
|
|
return dbHandle.close()
|
|
})
|
|
.catch((err) => {
|
|
console.log(err.message)
|
|
})
|
|
*/ |