cents/services/api/src/add-user.ts

27 lines
863 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { createUserWithPersonalLedger } from "./accounts.js";
import { initializeDatabase, pool } from "./db.js";
const name = process.argv[2]?.trim() ?? "";
const password = process.argv[3] ?? "";
if (!name || !password) {
throw new Error("用法npm run user:add -- <用户名> <密码>");
}
await initializeDatabase();
const client = await pool.connect();
try {
await client.query("BEGIN");
const user = await createUserWithPersonalLedger(client, name, password);
await client.query("COMMIT");
process.stdout.write(`已添加用户 ${user.name},并创建个人账本。\n`);
} catch (error) {
await client.query("ROLLBACK");
if (typeof error === "object" && error !== null && "code" in error && error.code === "23505") {
throw new Error("该用户名已存在");
}
throw error;
} finally {
client.release();
await pool.end();
}