minecluster/lib/database/queries/server-queries.js
2024-01-15 20:30:31 +00:00

128 lines
3 KiB
JavaScript

import pg from "../postgres.js";
import { deleteQuery, insertQuery, selectWhereQuery } from "../pg-query.js";
import ExpressClientError from "../../util/ExpressClientError.js";
const table = "servers";
const asExpressClientError = (e) => {
throw new ExpressClientError({ m: e.message, c: 409 });
};
const getMclName = (host, id) => `${host.replaceAll(".", "-")}-${id}`;
export async function createServerEntry(serverSpec) {
const {
name,
host,
version,
serverType: server_type,
memory,
backupHost: backup_host,
backupBucket: backup_bucket_path,
backupId: backup_id,
backupKey: backup_key,
backupInterval: backup_interval,
} = serverSpec;
var q = insertQuery(table, {
name,
host,
version,
server_type,
memory,
backup_enabled: !!backup_interval, // We already verified the payload, so any backup key will work
backup_host,
backup_bucket_path,
backup_id,
backup_key,
backup_interval,
});
q += "\n RETURNING *";
try {
const entries = await pg.query(q);
const {
id,
name,
host,
version,
server_type: serverType,
memory,
backup_enabled: backupEnabled,
backup_host: backupHost,
backup_bucket_path: backupPath,
backup_id: backupId,
backup_key: backupKey,
backup_interval: backupInterval,
} = entries[0];
const mclName = getMclName(host, id);
return {
name,
mclName,
id,
host,
version,
serverType,
memory,
backupEnabled,
backupHost,
backupPath,
backupId,
backupKey,
backupInterval,
};
} catch (e) {
asExpressClientError(e);
}
}
export async function deleteServerEntry(serverId) {
if (!serverId) asExpressClientError({ message: "Server ID Required!" });
const q = deleteQuery(table, { id: serverId });
return pg.query(q).catch(asExpressClientError);
}
export async function getServerEntry(serverId) {
if (!serverId) asExpressClientError({ message: "Server ID Required!" });
const q = selectWhereQuery(table, { id: serverId });
try {
const serverSpecs = await pg.query(q);
if (serverSpecs.length === 0) return [];
if (!serverSpecs.length === 1)
throw Error("Multiple servers found with the same name!");
const {
id,
name,
host,
version,
server_type: serverType,
memory,
backup_enabled: backupEnabled,
backup_host: backupHost,
backup_bucket_path: backupPath,
backup_id: backupId,
backup_key: backupKey,
backup_interval: backupInterval,
} = serverSpecs[0];
const mclName = getMclName(host, id);
return {
name,
mclName,
id,
host,
version,
serverType,
memory,
backupEnabled,
backupHost,
backupPath,
backupId,
backupKey,
backupInterval,
};
} catch (e) {
asExpressClientError(e);
}
}
export async function getServerEntries() {
const q = `SELECT * FROM ${table}`;
return pg.query(q);
}