seed-database.ts64 lines, 1.5 KB
| 1 | "use server"; |
| 2 | |
| 3 | import { seed } from "@/server/db/seed"; |
| 4 | import { ApiResponse } from "@/lib/types"; |
| 5 | import { auth } from "@/server/auth"; |
| 6 | import { revalidatePath } from "next/cache"; |
| 7 | |
| 8 | /** |
| 9 | * Server action to seed the database with test data |
| 10 | * This should only be used in development |
| 11 | */ |
| 12 | export async function seedDatabase(): Promise<ApiResponse<null>> { |
| 13 | try { |
| 14 | // Only allow in development environment |
| 15 | if (process.env.NODE_ENV !== "development") { |
| 16 | return { |
| 17 | success: false, |
| 18 | error: "This action is only available in development mode", |
| 19 | }; |
| 20 | } |
| 21 | |
| 22 | // Check if user is authenticated and has admin privileges |
| 23 | const session = await auth(); |
| 24 | if (!session?.user) { |
| 25 | return { |
| 26 | success: false, |
| 27 | error: "You must be logged in to perform this action", |
| 28 | }; |
| 29 | } |
| 30 | |
| 31 | // Check if user has admin role |
| 32 | if (session.user.role !== "admin") { |
| 33 | return { |
| 34 | success: false, |
| 35 | error: "You must have admin privileges to perform this action", |
| 36 | }; |
| 37 | } |
| 38 | |
| 39 | // Run the seed function |
| 40 | const result = await seed(); |
| 41 | |
| 42 | if (!result.success) { |
| 43 | return { |
| 44 | success: false, |
| 45 | error: "Failed to seed database", |
| 46 | }; |
| 47 | } |
| 48 | |
| 49 | // Revalidate all pages that might display the seeded data |
| 50 | revalidatePath("/"); |
| 51 | revalidatePath("/dashboard"); |
| 52 | |
| 53 | return { |
| 54 | success: true, |
| 55 | data: null, |
| 56 | }; |
| 57 | } catch (error) { |
| 58 | console.error("Error seeding database:", error); |
| 59 | return { |
| 60 | success: false, |
| 61 | error: "An unexpected error occurred", |
| 62 | }; |
| 63 | } |
| 64 | } |