generated from azures04/Base-REST-API
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.
78 lines
2.0 KiB
JavaScript
78 lines
2.0 KiB
JavaScript
const { pool } = require("../modules/database")
|
|
const { DefaultError } = require("../errors/errors")
|
|
|
|
async function findById(id) {
|
|
try {
|
|
const sql = "SELECT* FROM servers WHERE id = ?"
|
|
const rows = await pool.query(sql, [id])
|
|
return rows[0] || null
|
|
} catch (error) {
|
|
throw new DefaultError(500, "Internal Server Error", error)
|
|
}
|
|
}
|
|
|
|
async function findByUrl(url) {
|
|
try {
|
|
const sql = "SELECT* FROM servers WHERE url = ?"
|
|
const rows = await pool.query(sql, [url])
|
|
return rows[0] || null
|
|
} catch (error) {
|
|
throw new DefaultError(500, "Internal Server Error", error)
|
|
}
|
|
}
|
|
|
|
async function create(url, publicKey) {
|
|
try {
|
|
const sql = "INSERT INTO servers (serverUrl, publicKey) VALUES (?, ?)"
|
|
const rows = await pool.query(sql, [url, publicKey])
|
|
return rows[0] || null
|
|
} catch (error) {
|
|
throw new DefaultError(500, "Internal Server Error", error)
|
|
}
|
|
}
|
|
|
|
async function remove(id) {
|
|
try {
|
|
const sql = "DELETE FROM servers WHERE id = ?"
|
|
const rows = await pool.query(sql, [id])
|
|
return rows.affectedRows > 0
|
|
} catch (error) {
|
|
throw new DefaultError(500, "Internal Server Error", error)
|
|
}
|
|
}
|
|
|
|
async function updateServer(id, serverUrl, publicKey) {
|
|
try {
|
|
const fields = []
|
|
const params = { id }
|
|
|
|
if (serverUrl !== undefined) {
|
|
fields.push('`serverUrl` = :serverUrl')
|
|
params.serverUrl = serverUrl
|
|
}
|
|
|
|
if (publicKey !== undefined) {
|
|
fields.push('`publicKey` = :publicKey')
|
|
params.publicKey = publicKey
|
|
}
|
|
|
|
if (fields.length === 0) {
|
|
return findById(id)
|
|
}
|
|
|
|
const sql = `UPDATE servers SET ${fields.join(', ')} WHERE id = :id`
|
|
await pool.query(sql, params)
|
|
|
|
return findById(id)
|
|
} catch (error) {
|
|
throw new DefaultError(500, "Internal Server Error", error)
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
create,
|
|
remove,
|
|
findById,
|
|
findByUrl,
|
|
updateServer
|
|
} |