REFACTORED - migrate the data layer from Prisma to Drizzle (unify the stack)
- Add lib/db (Drizzle schema: 7 tables + 6 enums + relations, postgres.js client), drizzle.config.ts, lib/db/enums.ts (Prisma-compatible enum objects) - Rewrite all 14 app consumers + 4 admin components to Drizzle - Move the test DB layer to Drizzle + in-process PGlite; convert all 8 integration test files + factories (371 tests green) - Remove Prisma: deps, prisma/ schema+migrations, lib/prisma.ts, Dockerfile prisma generate; wire db:generate/migrate/push/studio to drizzle-kit; update Makefile - Preserve the old seed as scripts/legacy-prisma-seed.cjs (needs a Drizzle rewrite)
This commit is contained in:
+58
-37
@@ -1,6 +1,13 @@
|
||||
import { MediaKind, MediaSource, MediaUsageType, PortfolioSectionType } from "@prisma/client";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { db } from "@/lib/db";
|
||||
import {
|
||||
category,
|
||||
mediaAsset,
|
||||
mediaUsage,
|
||||
portfolioAsset,
|
||||
portfolioProject,
|
||||
portfolioSection,
|
||||
} from "@/lib/db/schema";
|
||||
import { MediaKind, MediaSource, MediaUsageType, PortfolioSectionType } from "@/lib/db/enums";
|
||||
|
||||
let counter = 0;
|
||||
function uniq(prefix: string) {
|
||||
@@ -8,11 +15,11 @@ function uniq(prefix: string) {
|
||||
return `${prefix}-${counter}`;
|
||||
}
|
||||
|
||||
export function createCategory(overrides: Record<string, unknown> = {}) {
|
||||
const slug = (overrides.slug as string) ?? uniq("cat");
|
||||
return prisma.category.create({
|
||||
data: {
|
||||
slug,
|
||||
export async function createCategory(overrides: Record<string, unknown> = {}) {
|
||||
const [row] = await db
|
||||
.insert(category)
|
||||
.values({
|
||||
slug: (overrides.slug as string) ?? uniq("cat"),
|
||||
nameAr: "الاسم",
|
||||
nameEn: "Name",
|
||||
nameDe: "Name",
|
||||
@@ -22,16 +29,19 @@ export function createCategory(overrides: Record<string, unknown> = {}) {
|
||||
sortOrder: 0,
|
||||
isActive: true,
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
} as typeof category.$inferInsert)
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function createProject(overrides: Record<string, unknown> = {}) {
|
||||
const categoryId = (overrides.categoryId as string) ?? (await createCategory()).id;
|
||||
const isPublished = (overrides.isPublished as boolean) ?? true;
|
||||
const slug = (overrides.slug as string) ?? uniq("proj");
|
||||
return prisma.portfolioProject.create({
|
||||
data: {
|
||||
const [row] = await db
|
||||
.insert(portfolioProject)
|
||||
.values({
|
||||
categoryId,
|
||||
slug,
|
||||
viewMode: "GRID",
|
||||
@@ -51,13 +61,16 @@ export async function createProject(overrides: Record<string, unknown> = {}) {
|
||||
...overrides,
|
||||
isPublished,
|
||||
publishedAt: isPublished ? new Date() : null,
|
||||
},
|
||||
});
|
||||
} as typeof portfolioProject.$inferInsert)
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
export function createSection(projectId: string, overrides: Record<string, unknown> = {}) {
|
||||
return prisma.portfolioSection.create({
|
||||
data: {
|
||||
export async function createSection(projectId: string, overrides: Record<string, unknown> = {}) {
|
||||
const [row] = await db
|
||||
.insert(portfolioSection)
|
||||
.values({
|
||||
projectId,
|
||||
type: PortfolioSectionType.RICH_TEXT,
|
||||
titleAr: "ع",
|
||||
@@ -68,13 +81,16 @@ export function createSection(projectId: string, overrides: Record<string, unkno
|
||||
bodyDe: "b",
|
||||
sortOrder: 0,
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
} as typeof portfolioSection.$inferInsert)
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
export function createAsset(projectId: string, overrides: Record<string, unknown> = {}) {
|
||||
return prisma.portfolioAsset.create({
|
||||
data: {
|
||||
export async function createAsset(projectId: string, overrides: Record<string, unknown> = {}) {
|
||||
const [row] = await db
|
||||
.insert(portfolioAsset)
|
||||
.values({
|
||||
projectId,
|
||||
kind: "IMAGE",
|
||||
filePath: "/uploads/media/assets/x.svg",
|
||||
@@ -83,35 +99,40 @@ export function createAsset(projectId: string, overrides: Record<string, unknown
|
||||
altDe: "a",
|
||||
sortOrder: 0,
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
} as typeof portfolioAsset.$inferInsert)
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
export function createMediaAsset(overrides: Record<string, unknown> = {}) {
|
||||
return prisma.mediaAsset.create({
|
||||
data: {
|
||||
export async function createMediaAsset(overrides: Record<string, unknown> = {}) {
|
||||
const [row] = await db
|
||||
.insert(mediaAsset)
|
||||
.values({
|
||||
source: MediaSource.EXTERNAL,
|
||||
kind: MediaKind.IMAGE,
|
||||
url: (overrides.url as string) ?? `https://cdn.example.com/${uniq("img")}.png`,
|
||||
fileName: "img.png",
|
||||
label: "Image",
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
} as typeof mediaAsset.$inferInsert)
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
export function createMediaUsage(
|
||||
assetId: string,
|
||||
overrides: Record<string, unknown> = {},
|
||||
) {
|
||||
return prisma.mediaUsage.create({
|
||||
data: {
|
||||
export async function createMediaUsage(assetId: string, overrides: Record<string, unknown> = {}) {
|
||||
const [row] = await db
|
||||
.insert(mediaUsage)
|
||||
.values({
|
||||
assetId,
|
||||
usageType: MediaUsageType.GENERIC,
|
||||
entityType: "test-entity",
|
||||
entityId: "e1",
|
||||
fieldKey: uniq("field"),
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
} as typeof mediaUsage.$inferInsert)
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
@@ -5,12 +5,12 @@ import path from "path";
|
||||
* Global integration setup.
|
||||
*
|
||||
* Only needed when running against a real Postgres via TEST_DATABASE_URL: reset the
|
||||
* schema and apply every migration once before the workers start. When
|
||||
* TEST_DATABASE_URL is not set, each worker spins up its own in-process PGlite database
|
||||
* (see tests/helpers/integration-setup.ts) and this is a no-op.
|
||||
* schema and apply every Drizzle migration once before the workers start. When
|
||||
* TEST_DATABASE_URL is not set, each worker spins up its own in-process PGlite
|
||||
* database (see tests/helpers/integration-setup.ts) and this is a no-op.
|
||||
*/
|
||||
|
||||
const MIGRATIONS_DIR = path.resolve(process.cwd(), "prisma", "migrations");
|
||||
const MIGRATIONS_DIR = path.resolve(process.cwd(), "lib", "db", "migrations");
|
||||
|
||||
export default async function setup() {
|
||||
const connectionString = process.env.TEST_DATABASE_URL?.trim();
|
||||
@@ -23,11 +23,11 @@ export default async function setup() {
|
||||
await client.connect();
|
||||
try {
|
||||
await client.query("DROP SCHEMA IF EXISTS public CASCADE; CREATE SCHEMA public;");
|
||||
const dirs = readdirSync(MIGRATIONS_DIR)
|
||||
.filter((entry) => /^\d/.test(entry))
|
||||
const files = readdirSync(MIGRATIONS_DIR)
|
||||
.filter((entry) => entry.endsWith(".sql"))
|
||||
.sort();
|
||||
for (const dir of dirs) {
|
||||
await client.query(readFileSync(path.join(MIGRATIONS_DIR, dir, "migration.sql"), "utf8"));
|
||||
for (const file of files) {
|
||||
await client.query(readFileSync(path.join(MIGRATIONS_DIR, file), "utf8"));
|
||||
}
|
||||
} finally {
|
||||
await client.end();
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
import { readFileSync, readdirSync } from "fs";
|
||||
import path from "path";
|
||||
|
||||
import { sql } from "drizzle-orm";
|
||||
import { afterAll, beforeEach, vi } from "vitest";
|
||||
|
||||
import * as schema from "@/lib/db/schema";
|
||||
|
||||
/**
|
||||
* Integration database wiring.
|
||||
* Integration database wiring (Drizzle).
|
||||
*
|
||||
* - If TEST_DATABASE_URL is set, the real `lib/prisma` singleton is used unchanged,
|
||||
* pointed at that Postgres (e.g. the Docker instance). Migrations are applied once
|
||||
* by the global setup; files run serially and truncate between tests.
|
||||
* - If TEST_DATABASE_URL is set, the real `@/lib/db` singleton is used unchanged,
|
||||
* pointed at that Postgres. Migrations are applied once by the global setup;
|
||||
* files run serially and truncate between tests.
|
||||
*
|
||||
* - Otherwise, `lib/prisma` is mocked with a Prisma client backed by an in-process
|
||||
* - Otherwise, `@/lib/db` is mocked with a Drizzle client backed by an in-process
|
||||
* PGlite database (Postgres compiled to WASM) — real Postgres semantics, fully
|
||||
* isolated per worker, no external server. Production code is never modified.
|
||||
*/
|
||||
@@ -20,44 +23,45 @@ if (realDbUrl) {
|
||||
process.env.DATABASE_URL = realDbUrl;
|
||||
}
|
||||
|
||||
vi.mock("@/lib/prisma", async () => {
|
||||
vi.mock("@/lib/db", async () => {
|
||||
if (process.env.TEST_DATABASE_URL?.trim()) {
|
||||
return await vi.importActual<typeof import("@/lib/prisma")>("@/lib/prisma");
|
||||
return await vi.importActual<typeof import("@/lib/db")>("@/lib/db");
|
||||
}
|
||||
|
||||
const { PGlite } = await import("@electric-sql/pglite");
|
||||
const { PrismaPGlite } = await import("pglite-prisma-adapter");
|
||||
const { PrismaClient } = await import("@prisma/client");
|
||||
const { drizzle } = await import("drizzle-orm/pglite");
|
||||
|
||||
const db = await PGlite.create();
|
||||
const migrationsDir = path.resolve(process.cwd(), "prisma", "migrations");
|
||||
const dirs = readdirSync(migrationsDir)
|
||||
.filter((entry) => /^\d/.test(entry))
|
||||
const client = new PGlite();
|
||||
const migrationsDir = path.resolve(process.cwd(), "lib", "db", "migrations");
|
||||
const files = readdirSync(migrationsDir)
|
||||
.filter((entry) => entry.endsWith(".sql"))
|
||||
.sort();
|
||||
for (const dir of dirs) {
|
||||
await db.exec(readFileSync(path.join(migrationsDir, dir, "migration.sql"), "utf8"));
|
||||
for (const file of files) {
|
||||
await client.exec(readFileSync(path.join(migrationsDir, file), "utf8"));
|
||||
}
|
||||
|
||||
const prisma = new PrismaClient({ adapter: new PrismaPGlite(db) });
|
||||
return { prisma };
|
||||
const db = drizzle(client, { schema });
|
||||
return { db, schema };
|
||||
});
|
||||
|
||||
const { prisma } = await import("@/lib/prisma");
|
||||
const { db } = await import("@/lib/db");
|
||||
|
||||
export { db };
|
||||
|
||||
// Truncated in dependency order (children first) between every test for isolation.
|
||||
const TABLES = [
|
||||
"MediaUsage",
|
||||
"MediaAsset",
|
||||
"PortfolioAsset",
|
||||
"PortfolioSection",
|
||||
"PortfolioProject",
|
||||
"Category",
|
||||
"AppConfig",
|
||||
"media_usage",
|
||||
"media_asset",
|
||||
"portfolio_asset",
|
||||
"portfolio_section",
|
||||
"portfolio_project",
|
||||
"category",
|
||||
"app_config",
|
||||
];
|
||||
|
||||
export async function resetDb() {
|
||||
const list = TABLES.map((table) => `"${table}"`).join(", ");
|
||||
await prisma.$executeRawUnsafe(`TRUNCATE TABLE ${list} RESTART IDENTITY CASCADE;`);
|
||||
await db.execute(sql.raw(`TRUNCATE TABLE ${list} RESTART IDENTITY CASCADE;`));
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
@@ -65,5 +69,6 @@ beforeEach(async () => {
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await prisma.$disconnect();
|
||||
// PGlite is in-process and torn down with the worker; the real postgres.js
|
||||
// client is a shared singleton and is left open on purpose.
|
||||
});
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { db } from "@/lib/db";
|
||||
import { appConfig, category } from "@/lib/db/schema";
|
||||
|
||||
describe("integration harness smoke test", () => {
|
||||
it("connects to the migrated test database and performs CRUD", async () => {
|
||||
const created = await prisma.category.create({
|
||||
data: {
|
||||
const [created] = await db
|
||||
.insert(category)
|
||||
.values({
|
||||
slug: "smoke",
|
||||
nameAr: "a",
|
||||
nameEn: "b",
|
||||
@@ -13,28 +16,27 @@ describe("integration harness smoke test", () => {
|
||||
descriptionAr: "a",
|
||||
descriptionEn: "b",
|
||||
descriptionDe: "c",
|
||||
},
|
||||
});
|
||||
})
|
||||
.returning();
|
||||
|
||||
expect(created.id).toBeTruthy();
|
||||
expect(created.isActive).toBe(true);
|
||||
|
||||
const found = await prisma.category.findUnique({ where: { slug: "smoke" } });
|
||||
const found = await db.query.category.findFirst({ where: eq(category.slug, "smoke") });
|
||||
expect(found?.nameEn).toBe("b");
|
||||
});
|
||||
|
||||
it("resets the database between tests", async () => {
|
||||
const count = await prisma.category.count();
|
||||
const count = await db.$count(category);
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("supports enums and appconfig upsert", async () => {
|
||||
await prisma.appConfig.upsert({
|
||||
where: { key: "k" },
|
||||
update: { value: "v2" },
|
||||
create: { key: "k", value: "v1" },
|
||||
});
|
||||
const row = await prisma.appConfig.findUnique({ where: { key: "k" } });
|
||||
await db
|
||||
.insert(appConfig)
|
||||
.values({ key: "k", value: "v1" })
|
||||
.onConflictDoUpdate({ target: appConfig.key, set: { value: "v2" } });
|
||||
const row = await db.query.appConfig.findFirst({ where: eq(appConfig.key, "k") });
|
||||
expect(row?.value).toBe("v1");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,8 +10,11 @@ vi.mock("@/lib/admin-auth", async () => {
|
||||
return { isAdminAuthenticated: m.isAdminAuthenticated, clearAdminSessionCookie: m.clearAdminSessionCookie };
|
||||
});
|
||||
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
import { createMediaAssetAction, deleteMediaAssetAction } from "@/app/_admin/media/actions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { db } from "@/lib/db";
|
||||
import { mediaAsset } from "@/lib/db/schema";
|
||||
import { removeManagedMediaFile } from "@/lib/media-storage";
|
||||
import { createMediaAsset, createMediaUsage } from "@/tests/helpers/factories";
|
||||
import { canManageUploads } from "@/tests/helpers/fs-capability";
|
||||
@@ -25,7 +28,7 @@ describe("createMediaAssetAction", () => {
|
||||
it("errors when no file is provided", async () => {
|
||||
const url = await captureRedirect(() => createMediaAssetAction(formDataFrom({ kind: "IMAGE", label: "L" })));
|
||||
expect(url).toContain("error=");
|
||||
expect(await prisma.mediaAsset.count()).toBe(0);
|
||||
expect(await db.$count(mediaAsset)).toBe(0);
|
||||
});
|
||||
|
||||
it.skipIf(!canManageUploads)("creates an asset from an uploaded file", async () => {
|
||||
@@ -34,7 +37,7 @@ describe("createMediaAssetAction", () => {
|
||||
createMediaAssetAction(formDataFrom({ kind: "IMAGE", label: "Pic", file })),
|
||||
);
|
||||
expect(url).toContain("success=");
|
||||
const assets = await prisma.mediaAsset.findMany();
|
||||
const assets = await db.select().from(mediaAsset);
|
||||
expect(assets.length).toBe(1);
|
||||
expect(assets[0].source).toBe("UPLOAD");
|
||||
await removeManagedMediaFile(assets[0].url);
|
||||
@@ -58,14 +61,14 @@ describe("deleteMediaAssetAction", () => {
|
||||
await createMediaUsage(asset.id);
|
||||
const url = await captureRedirect(() => deleteMediaAssetAction(formDataFrom({ assetId: asset.id })));
|
||||
expect(url).toContain("error=");
|
||||
expect(await prisma.mediaAsset.findUnique({ where: { id: asset.id } })).not.toBeNull();
|
||||
expect((await db.query.mediaAsset.findFirst({ where: eq(mediaAsset.id, asset.id) })) ?? null).not.toBeNull();
|
||||
});
|
||||
|
||||
it("deletes an unused external asset", async () => {
|
||||
const asset = await createMediaAsset({ url: "https://cdn/external.png" });
|
||||
const url = await captureRedirect(() => deleteMediaAssetAction(formDataFrom({ assetId: asset.id })));
|
||||
expect(url).toContain("success=");
|
||||
expect(await prisma.mediaAsset.findUnique({ where: { id: asset.id } })).toBeNull();
|
||||
expect((await db.query.mediaAsset.findFirst({ where: eq(mediaAsset.id, asset.id) })) ?? null).toBeNull();
|
||||
});
|
||||
|
||||
it("redirects unauthenticated callers to the admin root", async () => {
|
||||
|
||||
@@ -16,7 +16,15 @@ import {
|
||||
saveProjectAction,
|
||||
upsertCategoryAction,
|
||||
} from "@/app/_admin/portfolio/actions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
|
||||
import { db } from "@/lib/db";
|
||||
import {
|
||||
category as categoryTable,
|
||||
mediaUsage as mediaUsageTable,
|
||||
portfolioAsset as portfolioAssetTable,
|
||||
portfolioProject as portfolioProjectTable,
|
||||
} from "@/lib/db/schema";
|
||||
import { createCategory, createProject } from "@/tests/helpers/factories";
|
||||
import { adminAuth, captureRedirect, formDataFrom, resetNextMocks } from "@/tests/helpers/next-mocks";
|
||||
|
||||
@@ -81,7 +89,7 @@ describe("upsertCategoryAction", () => {
|
||||
it("creates a category", async () => {
|
||||
const url = await captureRedirect(() => upsertCategoryAction(categoryForm()));
|
||||
expect(url).toContain("success=");
|
||||
const category = await prisma.category.findUnique({ where: { slug: "branding" } });
|
||||
const category = await db.query.category.findFirst({ where: eq(categoryTable.slug, "branding") });
|
||||
expect(category?.nameEn).toBe("Branding");
|
||||
expect(category?.isActive).toBe(true);
|
||||
});
|
||||
@@ -92,7 +100,7 @@ describe("upsertCategoryAction", () => {
|
||||
upsertCategoryAction(categoryForm({ id: existing.id, slug: "old", nameEn: "Renamed" })),
|
||||
);
|
||||
expect(url).toContain("success=");
|
||||
const category = await prisma.category.findUnique({ where: { id: existing.id } });
|
||||
const category = await db.query.category.findFirst({ where: eq(categoryTable.id, existing.id) });
|
||||
expect(category?.nameEn).toBe("Renamed");
|
||||
});
|
||||
|
||||
@@ -121,14 +129,14 @@ describe("deleteCategoryAction", () => {
|
||||
await createProject({ categoryId: category.id });
|
||||
const url = await captureRedirect(() => deleteCategoryAction(formDataFrom({ id: category.id })));
|
||||
expect(url).toContain("error=");
|
||||
expect(await prisma.category.findUnique({ where: { id: category.id } })).not.toBeNull();
|
||||
expect((await db.query.category.findFirst({ where: eq(categoryTable.id, category.id) })) ?? null).not.toBeNull();
|
||||
});
|
||||
|
||||
it("deletes an empty category", async () => {
|
||||
const category = await createCategory();
|
||||
const url = await captureRedirect(() => deleteCategoryAction(formDataFrom({ id: category.id })));
|
||||
expect(url).toContain("success=");
|
||||
expect(await prisma.category.findUnique({ where: { id: category.id } })).toBeNull();
|
||||
expect((await db.query.category.findFirst({ where: eq(categoryTable.id, category.id) })) ?? null).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -138,16 +146,14 @@ describe("saveProjectAction", () => {
|
||||
const url = await captureRedirect(() => saveProjectAction(projectForm(category.id)));
|
||||
expect(url).toContain("success=");
|
||||
|
||||
const project = await prisma.portfolioProject.findUnique({ where: { slug: "case-study" } });
|
||||
const project = await db.query.portfolioProject.findFirst({ where: eq(portfolioProjectTable.slug, "case-study") });
|
||||
expect(project).not.toBeNull();
|
||||
expect(project?.isPublished).toBe(true);
|
||||
expect(project?.publishedAt).not.toBeNull();
|
||||
expect(project?.coverImagePath).toBe("https://cdn/cover.png");
|
||||
|
||||
expect(await prisma.portfolioAsset.count({ where: { projectId: project!.id } })).toBe(1);
|
||||
const usages = await prisma.mediaUsage.findMany({
|
||||
where: { entityType: "portfolio-project", entityId: project!.id },
|
||||
});
|
||||
expect(await db.$count(portfolioAssetTable, eq(portfolioAssetTable.projectId, project!.id))).toBe(1);
|
||||
const usages = await db.select().from(mediaUsageTable).where(and(eq(mediaUsageTable.entityType, "portfolio-project"), eq(mediaUsageTable.entityId, project!.id)));
|
||||
const usageTypes = usages.map((u) => u.usageType).sort();
|
||||
expect(usageTypes).toEqual(["PORTFOLIO_ASSET", "PORTFOLIO_COVER"]);
|
||||
});
|
||||
@@ -156,26 +162,26 @@ describe("saveProjectAction", () => {
|
||||
const category = await createCategory();
|
||||
const created = await captureRedirect(() => saveProjectAction(projectForm(category.id)));
|
||||
void created;
|
||||
const project = await prisma.portfolioProject.findUnique({ where: { slug: "case-study" } });
|
||||
const project = await db.query.portfolioProject.findFirst({ where: eq(portfolioProjectTable.slug, "case-study") });
|
||||
|
||||
const url = await captureRedirect(() =>
|
||||
saveProjectAction(projectForm(category.id, { id: project!.id, titleEn: "Updated Title" })),
|
||||
);
|
||||
expect(url).toContain("success=");
|
||||
const updated = await prisma.portfolioProject.findUnique({ where: { id: project!.id } });
|
||||
const updated = await db.query.portfolioProject.findFirst({ where: eq(portfolioProjectTable.id, project!.id) });
|
||||
expect(updated?.titleEn).toBe("Updated Title");
|
||||
// assets are replaced, not duplicated
|
||||
expect(await prisma.portfolioAsset.count({ where: { projectId: project!.id } })).toBe(1);
|
||||
expect(await db.$count(portfolioAssetTable, eq(portfolioAssetTable.projectId, project!.id))).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps the original publishedAt when re-saving an already published project", async () => {
|
||||
const category = await createCategory();
|
||||
await captureRedirect(() => saveProjectAction(projectForm(category.id)));
|
||||
const first = await prisma.portfolioProject.findUnique({ where: { slug: "case-study" } });
|
||||
const first = await db.query.portfolioProject.findFirst({ where: eq(portfolioProjectTable.slug, "case-study") });
|
||||
const originalPublishedAt = first!.publishedAt;
|
||||
|
||||
await captureRedirect(() => saveProjectAction(projectForm(category.id, { id: first!.id })));
|
||||
const second = await prisma.portfolioProject.findUnique({ where: { id: first!.id } });
|
||||
const second = await db.query.portfolioProject.findFirst({ where: eq(portfolioProjectTable.id, first!.id) });
|
||||
expect(second?.publishedAt?.toISOString()).toBe(originalPublishedAt?.toISOString());
|
||||
});
|
||||
|
||||
@@ -183,7 +189,7 @@ describe("saveProjectAction", () => {
|
||||
const category = await createCategory();
|
||||
const url = await captureRedirect(() => saveProjectAction(projectForm(category.id, { titleEn: "" })));
|
||||
expect(url).toContain("error=");
|
||||
expect(await prisma.portfolioProject.count()).toBe(0);
|
||||
expect(await db.$count(portfolioProjectTable)).toBe(0);
|
||||
});
|
||||
|
||||
it("reports a unique-constraint violation on duplicate slugs", async () => {
|
||||
@@ -206,7 +212,7 @@ describe("deleteProjectAction", () => {
|
||||
const project = await createProject();
|
||||
const url = await captureRedirect(() => deleteProjectAction(formDataFrom({ id: project.id })));
|
||||
expect(url).toContain("success=");
|
||||
expect(await prisma.portfolioProject.findUnique({ where: { id: project.id } })).toBeNull();
|
||||
expect((await db.query.portfolioProject.findFirst({ where: eq(portfolioProjectTable.id, project.id) })) ?? null).toBeNull();
|
||||
});
|
||||
|
||||
it("errors when the project does not exist", async () => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { GET as healthGet } from "@/app/api/health/route";
|
||||
import { GET as defaultLocaleGet } from "@/app/api/site/default-locale/route";
|
||||
import { setMaintenanceMode, updateSiteSettings, getSiteSettings } from "@/lib/app-config";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
@@ -20,7 +20,7 @@ describe("GET /api/health", () => {
|
||||
});
|
||||
|
||||
it("reports degraded (503) when the database query throws", async () => {
|
||||
vi.spyOn(prisma, "$queryRaw").mockRejectedValueOnce(new Error("db down"));
|
||||
vi.spyOn(db, "execute").mockRejectedValueOnce(new Error("db down"));
|
||||
const response = await healthGet();
|
||||
expect(response.status).toBe(503);
|
||||
const body = await response.json();
|
||||
|
||||
@@ -20,7 +20,10 @@ import {
|
||||
updateMarqueeSettings,
|
||||
updateSiteSettings,
|
||||
} from "@/lib/app-config";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
import { db } from "@/lib/db";
|
||||
import { appConfig, mediaUsage } from "@/lib/db/schema";
|
||||
import { createMediaAsset } from "@/tests/helpers/factories";
|
||||
|
||||
describe("maintenance mode", () => {
|
||||
@@ -31,7 +34,7 @@ describe("maintenance mode", () => {
|
||||
it("persists and reads back the enabled flag", async () => {
|
||||
await setMaintenanceMode(true);
|
||||
expect(await getMaintenanceMode()).toBe(true);
|
||||
const row = await prisma.appConfig.findUnique({ where: { key: MAINTENANCE_MODE_KEY } });
|
||||
const row = await db.query.appConfig.findFirst({ where: eq(appConfig.key, MAINTENANCE_MODE_KEY) });
|
||||
expect(row?.value).toBe("true");
|
||||
await setMaintenanceMode(false);
|
||||
expect(await getMaintenanceMode()).toBe(false);
|
||||
@@ -46,7 +49,7 @@ describe("site settings", () => {
|
||||
});
|
||||
|
||||
it("uses the stored siteName key as the fallback name", async () => {
|
||||
await prisma.appConfig.create({ data: { key: SITE_NAME_KEY, value: "My Studio" } });
|
||||
await db.insert(appConfig).values({ key: SITE_NAME_KEY, value: "My Studio" });
|
||||
const settings = await getSiteSettings();
|
||||
expect(settings.locales.ar.siteName).toBe("My Studio");
|
||||
});
|
||||
@@ -113,24 +116,20 @@ describe("getSiteSettingsMediaBindings", () => {
|
||||
it("maps media usages to their field bindings", async () => {
|
||||
const logo = await createMediaAsset({ url: "https://cdn/logo.png" });
|
||||
const favicon = await createMediaAsset({ url: "https://cdn/favicon.svg" });
|
||||
await prisma.mediaUsage.create({
|
||||
data: {
|
||||
await db.insert(mediaUsage).values({
|
||||
assetId: logo.id,
|
||||
usageType: "GENERIC",
|
||||
entityType: SITE_SETTINGS_ENTITY_TYPE,
|
||||
entityId: SITE_SETTINGS_ENTITY_ID,
|
||||
fieldKey: SITE_SETTINGS_LOGO_LIGHT_FIELD_KEY,
|
||||
},
|
||||
});
|
||||
await prisma.mediaUsage.create({
|
||||
data: {
|
||||
});
|
||||
await db.insert(mediaUsage).values({
|
||||
assetId: favicon.id,
|
||||
usageType: "GENERIC",
|
||||
entityType: SITE_SETTINGS_ENTITY_TYPE,
|
||||
entityId: SITE_SETTINGS_ENTITY_ID,
|
||||
fieldKey: SITE_SETTINGS_FAVICON_FIELD_KEY,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const bindings = await getSiteSettingsMediaBindings();
|
||||
expect(bindings.siteLogoLight?.assetId).toBe(logo.id);
|
||||
|
||||
@@ -2,9 +2,12 @@ import { readFile } from "fs/promises";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
import { resolveMediaSelection } from "@/lib/media-service";
|
||||
import { resolveMediaUploadPath } from "@/lib/media-storage";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { db } from "@/lib/db";
|
||||
import { mediaAsset } from "@/lib/db/schema";
|
||||
import { createMediaAsset } from "@/tests/helpers/factories";
|
||||
import { canManageUploads } from "@/tests/helpers/fs-capability";
|
||||
|
||||
@@ -47,7 +50,7 @@ describe("resolveMediaSelection — external mode", () => {
|
||||
expect(result.createdAssetId).toBeTruthy();
|
||||
expect(result.url).toBe("https://cdn/new/photo.png");
|
||||
|
||||
const stored = await prisma.mediaAsset.findUnique({ where: { id: result.assetId! } });
|
||||
const stored = await db.query.mediaAsset.findFirst({ where: eq(mediaAsset.id, result.assetId!) });
|
||||
expect(stored?.source).toBe("EXTERNAL");
|
||||
expect(stored?.fileName).toBe("photo.png");
|
||||
expect(stored?.label).toBe("Photo");
|
||||
@@ -108,7 +111,7 @@ describe("resolveMediaSelection — upload mode (filesystem)", () => {
|
||||
required: true,
|
||||
});
|
||||
expect(result.uploadedUrl).toBeTruthy();
|
||||
const stored = await prisma.mediaAsset.findUnique({ where: { id: result.assetId! } });
|
||||
const stored = await db.query.mediaAsset.findFirst({ where: eq(mediaAsset.id, result.assetId!) });
|
||||
expect(stored?.source).toBe("UPLOAD");
|
||||
// File actually written to disk
|
||||
const bytes = await readFile(resolveMediaUploadPath(result.url));
|
||||
|
||||
@@ -10,7 +10,8 @@ import {
|
||||
getPortfolioMediaBindings,
|
||||
replaceEntityMediaUsages,
|
||||
} from "@/lib/media";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { db } from "@/lib/db";
|
||||
import { mediaUsage } from "@/lib/db/schema";
|
||||
import { createMediaAsset as seedAsset } from "@/tests/helpers/factories";
|
||||
|
||||
describe("createMediaAsset / getMediaAssetById", () => {
|
||||
@@ -110,13 +111,11 @@ describe("getPortfolioMediaBindings", () => {
|
||||
const section = await seedAsset();
|
||||
const asset = await seedAsset();
|
||||
|
||||
await prisma.mediaUsage.createMany({
|
||||
data: [
|
||||
await db.insert(mediaUsage).values([
|
||||
{ assetId: cover.id, usageType: "PORTFOLIO_COVER", entityType: "portfolio-project", entityId: "proj", fieldKey: "cover" },
|
||||
{ assetId: section.id, usageType: "PORTFOLIO_SECTION", entityType: "portfolio-project", entityId: "proj", fieldKey: "sec_1" },
|
||||
{ assetId: asset.id, usageType: "PORTFOLIO_ASSET", entityType: "portfolio-project", entityId: "proj", fieldKey: "ast_1" },
|
||||
],
|
||||
});
|
||||
]);
|
||||
|
||||
const bindings = await getPortfolioMediaBindings("proj");
|
||||
expect(bindings.coverAssetId).toBe(cover.id);
|
||||
@@ -131,7 +130,5 @@ describe("getPortfolioMediaBindings", () => {
|
||||
});
|
||||
|
||||
async function createMediaUsageFor(assetId: string) {
|
||||
await prisma.mediaUsage.create({
|
||||
data: { assetId, usageType: "GENERIC", entityType: "e", entityId: "1", fieldKey: "f" },
|
||||
});
|
||||
await db.insert(mediaUsage).values({ assetId, usageType: "GENERIC", entityType: "e", entityId: "1", fieldKey: "f" });
|
||||
}
|
||||
|
||||
@@ -9,7 +9,10 @@ import {
|
||||
getPublishedPortfolioProjectBySlug,
|
||||
getPublishedPortfolioProjects,
|
||||
} from "@/lib/portfolio";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
import { db } from "@/lib/db";
|
||||
import { category, mediaUsage, portfolioAsset, portfolioProject, portfolioSection } from "@/lib/db/schema";
|
||||
import {
|
||||
createAsset,
|
||||
createCategory,
|
||||
@@ -75,15 +78,13 @@ describe("admin projects", () => {
|
||||
it("attaches media bindings to a project fetched by id", async () => {
|
||||
const project = await createProject();
|
||||
const cover = await createMediaAsset();
|
||||
await prisma.mediaUsage.create({
|
||||
data: {
|
||||
await db.insert(mediaUsage).values({
|
||||
assetId: cover.id,
|
||||
usageType: "PORTFOLIO_COVER",
|
||||
entityType: "portfolio-project",
|
||||
entityId: project.id,
|
||||
fieldKey: "cover",
|
||||
},
|
||||
});
|
||||
});
|
||||
const detail = await getAdminPortfolioProjectById(project.id);
|
||||
expect(detail?.coverMediaAssetId).toBe(cover.id);
|
||||
});
|
||||
@@ -127,15 +128,15 @@ describe("referential integrity", () => {
|
||||
it("restricts deleting a category that still has projects", async () => {
|
||||
const cat = await createCategory();
|
||||
await createProject({ categoryId: cat.id });
|
||||
await expect(prisma.category.delete({ where: { id: cat.id } })).rejects.toThrow();
|
||||
await expect(db.delete(category).where(eq(category.id, cat.id))).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("cascades section and asset deletion when a project is removed", async () => {
|
||||
const project = await createProject();
|
||||
await createSection(project.id);
|
||||
await createAsset(project.id);
|
||||
await prisma.portfolioProject.delete({ where: { id: project.id } });
|
||||
expect(await prisma.portfolioSection.count()).toBe(0);
|
||||
expect(await prisma.portfolioAsset.count()).toBe(0);
|
||||
await db.delete(portfolioProject).where(eq(portfolioProject.id, project.id));
|
||||
expect(await db.$count(portfolioSection)).toBe(0);
|
||||
expect(await db.$count(portfolioAsset)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user