Files
plp/prisma/seed.ts
T

99 lines
2.8 KiB
TypeScript

import { createHash } from "node:crypto";
import { PrismaClient } from "@prisma/client";
import {
assertSeedDatabaseAllowed,
DEFAULT_TEST_DATABASE_URL,
} from "./database-safety";
const databaseUrl = process.env.DATABASE_URL ?? DEFAULT_TEST_DATABASE_URL;
assertSeedDatabaseAllowed(databaseUrl);
const prisma = new PrismaClient({ datasources: { db: { url: databaseUrl } } });
const id = (value: string) => createHash("sha256").update(value).digest("hex");
async function seed(): Promise<void> {
const accounts = await Promise.all(
[
{
key: "demo-a",
nickname: "海风",
publicId: "00000000-0000-4000-8000-000000000001",
},
{
key: "demo-b",
nickname: "星河",
publicId: "00000000-0000-4000-8000-000000000002",
},
{
key: "demo-admin",
nickname: "管理员",
publicId: "00000000-0000-4000-8000-000000000003",
},
].map(({ key, nickname, publicId }) =>
prisma.account.upsert({
where: { phoneHmac: id(`drift-bottle:${key}:phone-hmac`) },
update: {
role: key === "demo-admin" ? "ADMIN" : "USER",
anonymousProfile: {
upsert: {
create: {
publicId,
nickname,
avatarColor: "#66CCFF",
reviewStatus: "APPROVED",
},
update: {
nickname,
avatarColor: "#66CCFF",
reviewStatus: "APPROVED",
},
},
},
},
create: {
role: key === "demo-admin" ? "ADMIN" : "USER",
phoneCiphertext: Buffer.from(
id(`drift-bottle:${key}:ciphertext`),
"hex",
),
phoneHmac: id(`drift-bottle:${key}:phone-hmac`),
anonymousProfile: {
create: {
publicId,
nickname,
avatarColor: "#66CCFF",
reviewStatus: "APPROVED",
},
},
},
}),
),
);
const author = accounts[0];
if (!author) throw new Error("Seed author was not created");
const bottleData = {
authorId: author.id,
contentText: "愿你今天遇见温柔。",
reviewStatus: "APPROVED" as const,
poolStatus: "IN_POOL" as const,
approvedAt: new Date(0),
};
await prisma.bottle.upsert({
where: { id: "00000000-0000-4000-8000-000000000101" },
update: bottleData,
create: { id: "00000000-0000-4000-8000-000000000101", ...bottleData },
});
console.info(
"Seed complete: 3 demo accounts (including admin), 3 anonymous profiles, 1 in-pool bottle.",
);
}
seed()
.catch((error: unknown) => {
void error;
console.error("Seed failed.");
process.exitCode = 1;
})
.finally(async () => prisma.$disconnect());