import { getPayload } from "payload"; import configPromise from "./payload.config"; import fs from "fs"; import path from "path"; import { fileURLToPath } from "url"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); async function run() { try { let payload; let retries = 5; while (retries > 0) { try { console.log( `Connecting to database (URI: ${process.env.DATABASE_URI || "default"})...`, ); payload = await getPayload({ config: configPromise }); break; } catch (e: any) { if ( e.code === "ECONNREFUSED" || e.code === "ENOTFOUND" || e.message?.includes("ECONNREFUSED") || e.message?.includes("ENOTFOUND") || e.message?.includes("cannot connect to Postgres") ) { console.log( `Database not ready (${e.code || "UNKNOWN"}), retrying in 3 seconds... (${retries} retries left)`, ); retries--; await new Promise((res) => setTimeout(res, 3000)); } else { console.error("Fatal connection error:", e); throw e; } } } if (!payload) { throw new Error( "Failed to connect to the database after multiple retries.", ); } const existing = await payload.find({ collection: "context-files", limit: 0, }); if (existing.totalDocs > 0) { console.log("Context collection already populated. Skipping seed."); process.exit(0); } const seedDir = path.resolve( __dirname, "src/payload/collections/ContextFiles/seed", ); if (!fs.existsSync(seedDir)) { console.log(`Seed directory not found at ${seedDir}`); process.exit(0); } const files = fs.readdirSync(seedDir).filter((f) => f.endsWith(".md")); let count = 0; for (const file of files) { const content = fs.readFileSync(path.join(seedDir, file), "utf8"); await payload.create({ collection: "context-files", data: { filename: file, content: content, }, }); count++; } console.log(`Seeded ${count} context files.`); process.exit(0); } catch (e) { console.error("Seeding failed:", e); process.exit(1); } } run();