Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions apps/web/src/__tests__/admin-reset-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ vi.mock('@copilotkit/outpost/db', () => ({

vi.mock('@copilotkit/outpost/shared', () => ({ verifyPassword: vi.fn() }));

const mockSeed = vi.fn();
vi.mock('@copilotkit/outpost/db/seed', () => ({
seed: (...a: unknown[]) => mockSeed(...a),
}));

import { POST } from '@/app/api/admin/reset/route';
import { authOptions } from '@/lib/auth';

Expand Down Expand Up @@ -69,4 +74,58 @@ describe('POST /api/admin/reset', () => {
authOptions.callbacks!.jwt!({ token: { memberId: 'admin-1', sv: 3 } } as never),
).resolves.toMatchObject({ memberId: 'admin-1' });
});

it('seeds the database when reseed is requested', async () => {
mockSeed.mockResolvedValue(undefined);

const res = await POST(
new Request('http://localhost:3000/api/admin/reset', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ confirmation: 'RESET', reseed: true }),
}),
);

expect(res.status).toBe(200);
expect(mockSeed).toHaveBeenCalledTimes(1);
// The seed runs on the client the route already holds, not a new one.
expect(mockSeed.mock.calls[0][0]).toEqual(
expect.objectContaining({ teamMember: expect.anything() }),
);
await expect(res.json()).resolves.toEqual({ success: true, reseeded: true });
});

it('does not seed when reseed is not requested', async () => {
const res = await POST(
new Request('http://localhost:3000/api/admin/reset', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ confirmation: 'RESET' }),
}),
);

expect(res.status).toBe(200);
expect(mockSeed).not.toHaveBeenCalled();
await expect(res.json()).resolves.toEqual({ success: true, reseeded: false });
});

it('reports a failed seed without discarding the reset', async () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
mockSeed.mockRejectedValue(new Error('seed failed'));

const res = await POST(
new Request('http://localhost:3000/api/admin/reset', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ confirmation: 'RESET', reseed: true }),
}),
);

expect(res.status).toBe(200);
expect(errorSpy).toHaveBeenCalled();
const body = await res.json();
expect(body.reseeded).toBe(false);
expect(body.note).toContain('npx prisma db seed');
errorSpy.mockRestore();
});
});
20 changes: 13 additions & 7 deletions apps/web/src/app/api/admin/reset/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { NextResponse } from 'next/server';
import { prisma } from '@copilotkit/outpost/db';
import { seed } from '@copilotkit/outpost/db/seed';
import { requireAdmin } from '@/lib/require-admin';

export async function POST(request: Request) {
Expand Down Expand Up @@ -59,19 +60,24 @@ export async function POST(request: Request) {
});
});

// Handle optional re-seed
// Handle optional re-seed. The seed runs after the reset transaction has
// committed: it writes its own rows, and a failure there must not roll
// back a reset the admin already asked for.
let reseeded = false;
let reseedNote: string | undefined;
if (reseed) {
// The seed script uses a top-level async IIFE with its own PrismaClient,
// so it cannot be cleanly imported. Manual re-seed is required.
reseeded = false;
try {
await seed(prisma);
reseeded = true;
} catch (error) {
console.error('[POST /api/admin/reset] Re-seed failed:', error);
reseedNote = 'The database was reset, but re-seeding failed. Run: npx prisma db seed';
}
}

return NextResponse.json({
success: true,
reseeded,
...(!reseeded && reseed
? { note: 'Manual re-seed required. Run: npx prisma db seed' }
: {}),
...(reseedNote ? { note: reseedNote } : {}),
});
}
20 changes: 20 additions & 0 deletions packages/outpost/db/src/seed-cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { PrismaClient } from '@prisma/client';
import { seed } from './seed.js';

/**
* CLI entry point: `pnpm db:seed` / `prisma db seed`.
*
* Importing `seed.ts` itself only defines the seed function, so this file
* owns the client and the process lifecycle.
*/
const prisma = new PrismaClient();

seed(prisma)
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
Loading