65 lines
1.9 KiB
JavaScript
Raw Normal View History

2021-01-13 12:07:33 +01:00
"use strict";
2021-01-13 13:02:27 +01:00
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const mariadb_1 = __importDefault(require("mariadb"));
2021-01-13 12:07:33 +01:00
let conn;
2021-01-13 13:02:27 +01:00
class DbHandle {
constructor() { }
async connect() {
this._conn = await mariadb_1.default.createConnection({
host: '172.16.10.18',
user: 'heroes',
password: 'test123',
database: 'heroes'
});
}
2021-01-13 15:23:04 +01:00
async getHeroes() {
2021-01-13 13:02:27 +01:00
var _a, _b;
2021-01-13 15:23:04 +01:00
const result = (_b = await ((_a = this._conn) === null || _a === void 0 ? void 0 : _a.query("SELECT id, name FROM hero"))) !== null && _b !== void 0 ? _b : Promise.reject(new Error('Connection not ready 1'));
return result.map((row) => {
var _a;
return { id: row.id, name: (_a = row.name) !== null && _a !== void 0 ? _a : 'unknown' };
});
2021-01-13 13:02:27 +01:00
}
close() {
var _a, _b;
return (_b = (_a = this._conn) === null || _a === void 0 ? void 0 : _a.end()) !== null && _b !== void 0 ? _b : Promise.reject(new Error('Connection not ready 2'));
}
}
/*
2021-01-13 15:23:04 +01:00
const dbHandle = new DbHandle()
2021-01-13 13:02:27 +01:00
dbHandle.connect()
.then(() => dbHandle.get("SELECT * FROM hero"))
.then((result) => {
console.log(result)
return dbHandle.close()
2021-01-13 12:07:33 +01:00
})
2021-01-13 13:02:27 +01:00
.catch((err) => {
console.log(err)
2021-01-13 15:23:04 +01:00
})
2021-01-13 13:02:27 +01:00
*/
2021-01-13 15:23:04 +01:00
async function exec() {
const dbHandle = new DbHandle();
try {
await dbHandle.connect();
const heroes = await dbHandle.getHeroes();
console.log(heroes);
}
finally {
await dbHandle.close();
}
}
exec().catch((err) => console.log(err.message));
/*
2021-01-13 13:02:27 +01:00
dbHandle.get("SELECT * FROM hero")
.then((result) => {
2021-01-13 15:23:04 +01:00
console.log(result)
return dbHandle.close()
})
2021-01-13 13:02:27 +01:00
.catch((err) => {
2021-01-13 15:23:04 +01:00
console.log(err.message)
})
*/