generated from azures04/Base-REST-API
Add MariaDB integration and repositories
Introduce DB support and repos: add modules/database.js (connection pool + runDDL) and SQL DDL files (data/ddl/*) for servers, users, providers, identities and credentials. Add repository layers: users, servers, providers, identities, credentials. Update server.js to run DDL at startup. Update .env.example with DB settings and bump dependencies in package.json/package-lock.json (add mariadb, bump dotenv/helmet/path-to-regexp/zod and dev tool upgrades). Error handling and logging included for DDL and repo operations.
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
const mariadb = require("mariadb")
|
||||
const logger = require("./logger")
|
||||
const fs = require("fs/promises")
|
||||
const path = require("path")
|
||||
|
||||
const dbConfig = {
|
||||
host: process.env.DATABASE_HOST,
|
||||
user: process.env.DATABASE_USER,
|
||||
password: process.env.DATABASE_PASSWORD,
|
||||
database: process.env.DATABASE_NAME,
|
||||
acquireTimeout: 20000,
|
||||
connectTimeout: 20000,
|
||||
bigIntAsNumber: true,
|
||||
insertIdAsNumber: true,
|
||||
decimalAsNumber: true
|
||||
}
|
||||
|
||||
const pool = mariadb.createPool({
|
||||
...dbConfig,
|
||||
connectionLimit: Number(process.env.DATABASE_CONNECTION_LIMIT) || 10
|
||||
})
|
||||
|
||||
async function runDDL() {
|
||||
let conn
|
||||
try {
|
||||
conn = await mariadb.createConnection({
|
||||
...dbConfig,
|
||||
multipleStatements: true
|
||||
})
|
||||
|
||||
const ddlDir = path.join(process.cwd(), "data", "ddl")
|
||||
const files = await fs.readdir(ddlDir)
|
||||
|
||||
const sqlFiles = files
|
||||
.filter(file => file.endsWith(".sql"))
|
||||
.sort()
|
||||
|
||||
for (const file of sqlFiles) {
|
||||
const filePath = path.join(ddlDir, file)
|
||||
const sql = await fs.readFile(filePath, "utf-8")
|
||||
|
||||
if (sql.trim()) {
|
||||
logger.log(`Execution of ${file.bold}`, ["DDL", "yellow"])
|
||||
await conn.query(sql)
|
||||
}
|
||||
}
|
||||
logger.log("Initialization of tables done.", ["DDL", "yellow"])
|
||||
} catch (error) {
|
||||
logger.error("Error while executing scripts :", ["DDL", "yellow"])
|
||||
logger.error(error)
|
||||
throw error
|
||||
} finally {
|
||||
if (conn) {
|
||||
await conn.end()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
pool,
|
||||
runDDL
|
||||
}
|
||||
Reference in New Issue
Block a user