ai-chatbot/scripts/system-settings/create-snapshot.ts
2026-05-29 16:52:40 +08:00

84 lines
2.3 KiB
TypeScript

import { config as loadEnv } from "dotenv";
import { inArray } from "drizzle-orm";
loadEnv({ path: ".env.local" });
function readArg(name: string) {
const prefix = `${name}=`;
const match = process.argv.find((arg) => arg.startsWith(prefix));
return match ? match.slice(prefix.length) : null;
}
async function main() {
const scopeArg = readArg("--scope");
const label = readArg("--label");
if (!scopeArg) {
throw new Error("Usage: pnpm tsx scripts/system-settings/create-snapshot.ts --scope=<scope> [--label=<label>]");
}
const dbModule = await import("../../lib/db");
const schemaModule = await import("../../lib/db/schema");
const snapshotModule = await import("../../lib/system-settings/snapshot");
const { db } = dbModule;
const { systemSettingSnapshot, systemSettings } = schemaModule;
const {
createSystemSettingSnapshotData,
getSystemSettingSnapshotScopeKeys,
summarizeSystemSettingSnapshotData,
} = snapshotModule;
const keys = getSystemSettingSnapshotScopeKeys(
scopeArg as keyof typeof snapshotModule.SYSTEM_SETTING_SNAPSHOT_SCOPES
);
const rows = await db
.select({
key: systemSettings.key,
value: systemSettings.value,
})
.from(systemSettings)
.where(inArray(systemSettings.key, [...keys]));
const valueByKey = new Map(rows.map((row) => [row.key, row.value]));
const snapshotData = createSystemSettingSnapshotData(
scopeArg as keyof typeof snapshotModule.SYSTEM_SETTING_SNAPSHOT_SCOPES,
valueByKey
);
const [snapshot] = await db
.insert(systemSettingSnapshot)
.values({
scope: scopeArg,
label: label || `manual-${scopeArg}-snapshot`,
summary: summarizeSystemSettingSnapshotData(snapshotData),
data: snapshotData,
createdAt: new Date(),
createdBy: null,
})
.returning({
id: systemSettingSnapshot.id,
scope: systemSettingSnapshot.scope,
label: systemSettingSnapshot.label,
createdAt: systemSettingSnapshot.createdAt,
});
console.log(
JSON.stringify(
{
snapshotId: snapshot?.id ?? null,
scope: snapshot?.scope ?? scopeArg,
label: snapshot?.label ?? label ?? null,
createdAt: snapshot?.createdAt ?? null,
keyCount: keys.length,
},
null,
2
)
);
}
main().catch((error) => {
console.error(error);
process.exit(1);
});