140 lines
4.4 KiB
TypeScript
140 lines
4.4 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { readdir, readFile } from "node:fs/promises";
|
|
import path from "node:path";
|
|
|
|
import { PostgreSqlContainer, type StartedPostgreSqlContainer } from "@testcontainers/postgresql";
|
|
import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
import { Pool } from "pg";
|
|
|
|
import * as schema from "@/db/schema";
|
|
|
|
type DownloadSeed = {
|
|
editorialId: string;
|
|
usageId: string;
|
|
assetId: string;
|
|
};
|
|
|
|
export type PostgresTestDatabase = {
|
|
database: NodePgDatabase<typeof schema>;
|
|
pool: Pool;
|
|
seedEditorialWithUsage(): Promise<DownloadSeed>;
|
|
insertDownload(
|
|
input: DownloadSeed & {
|
|
id?: string;
|
|
idempotencyKey: string;
|
|
intentKind?: "new_usage" | "repeat_download";
|
|
},
|
|
): Promise<void>;
|
|
applyRemainingMigrations(): Promise<void>;
|
|
stop(): Promise<void>;
|
|
};
|
|
|
|
export async function startPostgres(
|
|
{
|
|
through,
|
|
migrationsDir,
|
|
alsoApply = [],
|
|
}: { through?: string; migrationsDir?: string; alsoApply?: string[] } = {},
|
|
): Promise<PostgresTestDatabase> {
|
|
const container = await new PostgreSqlContainer("postgres:17-alpine")
|
|
.withDatabase("portal")
|
|
.withUsername("portal")
|
|
.withPassword("portal")
|
|
.start();
|
|
const pool = new Pool({ connectionString: container.getConnectionUri() });
|
|
|
|
const migrationFiles = await listMigrationFiles(migrationsDir);
|
|
const throughIndex = through ? migrationFiles.indexOf(through) : migrationFiles.length - 1;
|
|
if (through && throughIndex < 0) throw new Error(`Unknown migration: ${through}`);
|
|
let appliedMigrationCount = throughIndex + 1;
|
|
await applyMigrationFiles(pool, migrationsDir, migrationFiles.slice(0, appliedMigrationCount));
|
|
// Additive current-chain migrations (new tables/columns) that the historical
|
|
// chain predates, so current service code can run against the old schema.
|
|
for (const file of alsoApply) {
|
|
await pool.query(await readFile(path.join(process.cwd(), file), "utf8"));
|
|
}
|
|
|
|
const db = drizzle({ client: pool, schema });
|
|
|
|
return {
|
|
database: db,
|
|
pool,
|
|
async seedEditorialWithUsage() {
|
|
return seedEditorialWithUsage(db);
|
|
},
|
|
async insertDownload(input) {
|
|
await db.insert(schema.downloadEvents).values({
|
|
id: input.id,
|
|
editorialAccountId: input.editorialId,
|
|
usageId: input.usageId,
|
|
immichAssetId: input.assetId,
|
|
requestId: randomUUID(),
|
|
idempotencyKey: input.idempotencyKey,
|
|
requestFingerprint: "0".repeat(64),
|
|
intentKind: input.intentKind ?? "new_usage",
|
|
});
|
|
},
|
|
async applyRemainingMigrations() {
|
|
await applyMigrationFiles(pool, migrationsDir, migrationFiles.slice(appliedMigrationCount));
|
|
appliedMigrationCount = migrationFiles.length;
|
|
},
|
|
async stop() {
|
|
await pool.end();
|
|
await stopContainer(container);
|
|
},
|
|
};
|
|
}
|
|
|
|
async function listMigrationFiles(migrationsDir?: string) {
|
|
const migrationDirectory = path.join(process.cwd(), migrationsDir ?? "drizzle");
|
|
return (await readdir(migrationDirectory))
|
|
.filter((file) => /^\d+_.*\.sql$/.test(file))
|
|
.sort();
|
|
}
|
|
|
|
async function applyMigrationFiles(pool: Pool, migrationsDir: string | undefined, migrationFiles: string[]) {
|
|
const migrationDirectory = path.join(process.cwd(), migrationsDir ?? "drizzle");
|
|
for (const file of migrationFiles) {
|
|
await pool.query(await readFile(path.join(migrationDirectory, file), "utf8"));
|
|
}
|
|
}
|
|
|
|
async function seedEditorialWithUsage(db: NodePgDatabase<typeof schema>): Promise<DownloadSeed> {
|
|
const userId = randomUUID();
|
|
const editorialId = randomUUID();
|
|
const usageId = randomUUID();
|
|
const assetId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
|
|
|
await db.insert(schema.users).values({
|
|
id: userId,
|
|
name: "Test Redaktion",
|
|
email: `test-${userId}@example.com`,
|
|
emailVerified: true,
|
|
});
|
|
await db.insert(schema.editorialAccounts).values({
|
|
id: editorialId,
|
|
userId,
|
|
name: "Test Redaktion",
|
|
contactName: "Testkontakt",
|
|
loginEmail: `test-${userId}@example.com`,
|
|
status: "active",
|
|
currentPriceCents: 1500,
|
|
});
|
|
await db.insert(schema.usages).values({
|
|
id: usageId,
|
|
editorialAccountId: editorialId,
|
|
immichAssetId: assetId,
|
|
filenameSnapshot: "bild.jpg",
|
|
immichAlbumIdSnapshot: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
|
|
albumNameSnapshot: "Presse",
|
|
purpose: "Artikel",
|
|
priceCents: 1500,
|
|
});
|
|
|
|
return { editorialId, usageId, assetId };
|
|
}
|
|
|
|
async function stopContainer(container: StartedPostgreSqlContainer) {
|
|
await container.stop();
|
|
}
|