chore(db): remove Prisma facade and drop prisma:generate from CI
Co-authored-by: Cursor <[email protected]>
This commit is contained in:
1 parent
ca72966a37
commit
422567272c
17 files changed
+182
-1430
No files matched your search
@@ -1,15 +1,50 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const create = vi.hoisted(() => vi.fn());
|
||||
const findMany = vi.hoisted(() => vi.fn());
|
||||
const count = vi.hoisted(() => vi.fn());
|
||||
const userFindMany = vi.hoisted(() => vi.fn());
|
||||
const insertValues = vi.hoisted(() => vi.fn());
|
||||
const selectRows = vi.hoisted(() => vi.fn());
|
||||
const selectCount = vi.hoisted(() => vi.fn());
|
||||
const selectUsers = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("@/lib/prisma", () => ({
|
||||
prisma: {
|
||||
adminAuditLog: { create, findMany, count },
|
||||
user: { findMany: userFindMany },
|
||||
vi.mock("@/lib/db", () => ({
|
||||
db: {
|
||||
insert: vi.fn(() => ({ values: insertValues })),
|
||||
select: vi.fn((fields?: { value?: unknown; id?: unknown }) => {
|
||||
// count() query passes { value: count() }; user lookup passes { id, username }
|
||||
if (fields && "value" in fields && !("id" in fields)) {
|
||||
return {
|
||||
from: () => ({
|
||||
where: () => selectCount(),
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (fields && "id" in fields && "username" in fields) {
|
||||
return {
|
||||
from: () => ({
|
||||
where: () => selectUsers(),
|
||||
}),
|
||||
};
|
||||
}
|
||||
// default: audit log rows
|
||||
return {
|
||||
from: () => ({
|
||||
where: () => ({
|
||||
orderBy: () => ({
|
||||
limit: () => ({
|
||||
offset: () => selectRows(),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
AdminAuditLog: {
|
||||
id: "id",
|
||||
userId: "userId",
|
||||
action: "action",
|
||||
target: "target",
|
||||
},
|
||||
User: { id: "id", username: "username" },
|
||||
}));
|
||||
|
||||
vi.mock("@/env", () => ({ env: {} }));
|
||||
@@ -22,14 +57,14 @@ beforeEach(() => {
|
||||
|
||||
describe("logAudit", () => {
|
||||
it("creates an audit entry", async () => {
|
||||
create.mockResolvedValue({ id: 1 });
|
||||
insertValues.mockResolvedValue({ id: 1 });
|
||||
await logAudit({
|
||||
userId: 1,
|
||||
action: "test_action",
|
||||
target: "user",
|
||||
targetId: 42,
|
||||
});
|
||||
const data = create.mock.calls[0][0].data;
|
||||
const data = insertValues.mock.calls[0][0];
|
||||
expect(data.userId).toBe(1);
|
||||
expect(data.action).toBe("test_action");
|
||||
expect(data.target).toBe("user");
|
||||
@@ -37,7 +72,7 @@ describe("logAudit", () => {
|
||||
});
|
||||
|
||||
it("redacts sensitive keys in payload", async () => {
|
||||
create.mockResolvedValue({ id: 1 });
|
||||
insertValues.mockResolvedValue({ id: 1 });
|
||||
await logAudit({
|
||||
userId: 1,
|
||||
action: "update",
|
||||
@@ -46,32 +81,32 @@ describe("logAudit", () => {
|
||||
before: { username: "foo", password: "secret123" },
|
||||
after: { username: "bar", password: "newsecret" },
|
||||
});
|
||||
const data = create.mock.calls[0][0].data;
|
||||
const data = insertValues.mock.calls[0][0];
|
||||
expect(JSON.parse(data.before).password).toBe("[Redacted]");
|
||||
expect(JSON.parse(data.after).password).toBe("[Redacted]");
|
||||
expect(JSON.parse(data.diff).username).toEqual({ from: "foo", to: "bar" });
|
||||
});
|
||||
|
||||
it("omits diff when only before or after is missing", async () => {
|
||||
create.mockResolvedValue({ id: 1 });
|
||||
insertValues.mockResolvedValue({ id: 1 });
|
||||
await logAudit({
|
||||
userId: 1,
|
||||
action: "delete",
|
||||
target: "user",
|
||||
before: { username: "foo" },
|
||||
});
|
||||
const data = create.mock.calls[0][0].data;
|
||||
const data = insertValues.mock.calls[0][0];
|
||||
expect(data.diff).toBeNull();
|
||||
});
|
||||
|
||||
it("handles empty payloads", async () => {
|
||||
create.mockResolvedValue({ id: 1 });
|
||||
insertValues.mockResolvedValue({ id: 1 });
|
||||
await logAudit({ userId: 1, action: "view", target: "page" });
|
||||
expect(create).toHaveBeenCalledOnce();
|
||||
expect(insertValues).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("flattens nested objects", async () => {
|
||||
create.mockResolvedValue({ id: 1 });
|
||||
insertValues.mockResolvedValue({ id: 1 });
|
||||
await logAudit({
|
||||
userId: 1,
|
||||
action: "update_settings",
|
||||
@@ -79,14 +114,14 @@ describe("logAudit", () => {
|
||||
before: { nested: { key: "val" } },
|
||||
after: {},
|
||||
});
|
||||
const data = create.mock.calls[0][0].data;
|
||||
const data = insertValues.mock.calls[0][0];
|
||||
expect(JSON.parse(data.before)).toEqual({ nested: { key: "val" } });
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAuditLogs", () => {
|
||||
it("returns paginated logs with usernames", async () => {
|
||||
findMany.mockResolvedValue([
|
||||
selectRows.mockResolvedValue([
|
||||
{
|
||||
id: 1,
|
||||
userId: 1,
|
||||
@@ -110,8 +145,8 @@ describe("getAuditLogs", () => {
|
||||
createdAt: "2024-01-02",
|
||||
},
|
||||
]);
|
||||
count.mockResolvedValue(2);
|
||||
userFindMany.mockResolvedValue([
|
||||
selectCount.mockResolvedValue([{ value: 2 }]);
|
||||
selectUsers.mockResolvedValue([
|
||||
{ id: 1, username: "alice" },
|
||||
{ id: 2, username: "bob" },
|
||||
]);
|
||||
@@ -125,23 +160,15 @@ describe("getAuditLogs", () => {
|
||||
});
|
||||
|
||||
it("filters by search term", async () => {
|
||||
findMany.mockResolvedValue([]);
|
||||
count.mockResolvedValue(0);
|
||||
selectRows.mockResolvedValue([]);
|
||||
selectCount.mockResolvedValue([{ value: 0 }]);
|
||||
await getAuditLogs({ search: "test" });
|
||||
expect(findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
OR: [
|
||||
{ action: { contains: "test" } },
|
||||
{ target: { contains: "test" } },
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(selectRows).toHaveBeenCalled();
|
||||
expect(selectCount).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("falls back to User #id for unknown users", async () => {
|
||||
findMany.mockResolvedValue([
|
||||
selectRows.mockResolvedValue([
|
||||
{
|
||||
id: 1,
|
||||
userId: 99,
|
||||
@@ -154,8 +181,8 @@ describe("getAuditLogs", () => {
|
||||
createdAt: "2024-01-01",
|
||||
},
|
||||
]);
|
||||
count.mockResolvedValue(1);
|
||||
userFindMany.mockResolvedValue([]);
|
||||
selectCount.mockResolvedValue([{ value: 1 }]);
|
||||
selectUsers.mockResolvedValue([]);
|
||||
const result = await getAuditLogs();
|
||||
expect(result.rows[0].username).toBe("User #99");
|
||||
});
|
||||
|
||||
+34
-31
@@ -1,4 +1,5 @@
|
||||
import { prisma } from "../prisma";
|
||||
import { count, desc, inArray, like, or } from "drizzle-orm";
|
||||
import { AdminAuditLog, db, User } from "@/lib/db";
|
||||
|
||||
interface AuditEntry {
|
||||
userId: number;
|
||||
@@ -55,17 +56,15 @@ export async function logAudit(entry: AuditEntry): Promise<void> {
|
||||
: undefined;
|
||||
const diff = computeDiff(sanitizedBefore, sanitizedAfter);
|
||||
|
||||
await prisma.adminAuditLog.create({
|
||||
data: {
|
||||
userId: entry.userId,
|
||||
action: entry.action,
|
||||
target: entry.target,
|
||||
targetId: entry.targetId,
|
||||
before: sanitizedBefore ? JSON.stringify(sanitizedBefore) : null,
|
||||
after: sanitizedAfter ? JSON.stringify(sanitizedAfter) : null,
|
||||
diff: diff ? JSON.stringify(diff) : null,
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
await db.insert(AdminAuditLog).values({
|
||||
userId: entry.userId,
|
||||
action: entry.action,
|
||||
target: entry.target,
|
||||
targetId: entry.targetId,
|
||||
before: sanitizedBefore ? JSON.stringify(sanitizedBefore) : null,
|
||||
after: sanitizedAfter ? JSON.stringify(sanitizedAfter) : null,
|
||||
diff: diff ? JSON.stringify(diff) : null,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -80,29 +79,33 @@ export async function getAuditLogs(options: GetLogsOptions = {}) {
|
||||
const skip = (page - 1) * perPage;
|
||||
|
||||
const where = search
|
||||
? {
|
||||
OR: [
|
||||
{ action: { contains: search } },
|
||||
{ target: { contains: search } },
|
||||
],
|
||||
}
|
||||
: {};
|
||||
? or(
|
||||
like(AdminAuditLog.action, `%${search}%`),
|
||||
like(AdminAuditLog.target, `%${search}%`),
|
||||
)
|
||||
: undefined;
|
||||
|
||||
const [rows, total] = await Promise.all([
|
||||
prisma.adminAuditLog.findMany({
|
||||
where,
|
||||
orderBy: { id: "desc" },
|
||||
skip,
|
||||
take: perPage,
|
||||
}),
|
||||
prisma.adminAuditLog.count({ where }),
|
||||
const [rows, totalResult] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
.from(AdminAuditLog)
|
||||
.where(where)
|
||||
.orderBy(desc(AdminAuditLog.id))
|
||||
.limit(perPage)
|
||||
.offset(skip),
|
||||
db.select({ value: count() }).from(AdminAuditLog).where(where),
|
||||
]);
|
||||
|
||||
const total = Number(totalResult[0]?.value ?? 0);
|
||||
|
||||
const userIds = [...new Set(rows.map((r) => r.userId))];
|
||||
const users = await prisma.user.findMany({
|
||||
where: { id: { in: userIds } },
|
||||
select: { id: true, username: true },
|
||||
});
|
||||
const users =
|
||||
userIds.length > 0
|
||||
? await db
|
||||
.select({ id: User.id, username: User.username })
|
||||
.from(User)
|
||||
.where(inArray(User.id, userIds))
|
||||
: [];
|
||||
const userMap = new Map(users.map((u) => [u.id, u.username]));
|
||||
|
||||
const enrichedRows = rows.map((r) => ({
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const findUnique = vi.hoisted(() => vi.fn());
|
||||
const selectLimit = vi.hoisted(() => vi.fn().mockResolvedValue([]));
|
||||
const mockFetch = vi.hoisted(() => vi.fn().mockResolvedValue({ ok: true }));
|
||||
|
||||
vi.mock("@/lib/prisma", () => ({
|
||||
prisma: { websiteSetting: { findUnique } },
|
||||
vi.mock("@/lib/db", () => ({
|
||||
db: {
|
||||
select: vi.fn(() => ({
|
||||
from: vi.fn(() => ({
|
||||
where: vi.fn(() => ({
|
||||
limit: selectLimit,
|
||||
})),
|
||||
})),
|
||||
})),
|
||||
},
|
||||
WebsiteSetting: { key: "key", value: "value" },
|
||||
}));
|
||||
|
||||
vi.mock("@/env", () => ({
|
||||
@@ -21,7 +30,6 @@ import { notify } from "./webhook";
|
||||
|
||||
describe("webhook", () => {
|
||||
it("sends a Discord notification when webhook URL is configured", async () => {
|
||||
findUnique.mockResolvedValue(null);
|
||||
notify({
|
||||
action: "ban",
|
||||
actor: "admin",
|
||||
@@ -41,7 +49,6 @@ describe("webhook", () => {
|
||||
|
||||
it("does not throw when fetch fails", async () => {
|
||||
mockFetch.mockRejectedValueOnce(new Error("network error"));
|
||||
findUnique.mockResolvedValue(null);
|
||||
expect(() =>
|
||||
notify({ action: "ban", actor: "admin", target: "user1" }),
|
||||
).not.toThrow();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { env } from "@/env";
|
||||
import { db, WebsiteSetting } from "@/lib/db";
|
||||
import { logger } from "@/lib/logger";
|
||||
import { prisma } from "../prisma";
|
||||
|
||||
export type { WebhookAction } from "@/types/admin";
|
||||
|
||||
@@ -40,9 +41,11 @@ async function getSetting(
|
||||
): Promise<string | null> {
|
||||
if (envValue) return envValue;
|
||||
try {
|
||||
const setting = await prisma.websiteSetting.findUnique({
|
||||
where: { key: cmsKey },
|
||||
});
|
||||
const [setting] = await db
|
||||
.select({ value: WebsiteSetting.value })
|
||||
.from(WebsiteSetting)
|
||||
.where(eq(WebsiteSetting.key, cmsKey))
|
||||
.limit(1);
|
||||
return setting?.value || null;
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
Reference in new issue
Block a user