rg_backend_academy/lecture_4/employees-cli/departments-update.js

41 lines
975 B
JavaScript

import client from "./db-client.js";
import prompt from "prompt-sync";
const promptSync = prompt();
try {
await client.connect();
const id = Number(promptSync("Enter the ID of the department you want to update: "));
const newName = promptSync("Enter the new name of the department: ").trim();
if (!Number.isInteger(id) || id <= 0) {
throw new Error("Department ID must be a positive integer.");
}
if (!newName) {
throw new Error("Department name cannot be empty.");
}
// RETURNING avoids a separate query for checking whether the department exists.
const result = await client.query(
`UPDATE department
SET name = $1
WHERE id = $2
RETURNING id, name`,
[newName, id],
);
if (result.rows.length === 0) {
throw new Error(`Department with ID ${id} not found.`);
}
console.log("Updated department:");
console.table(result.rows[0]);
} catch (error) {
console.error(error.message);
process.exitCode = 1;
} finally {
await client.end();
}