/** * MITHOME-136: one-off content transfer MongoDB → PostgreSQL, in two steps * so that only one Payload instance runs per process and the bundle can be * reviewed (and reused to seed a fresh database). * * export — reads through the shared config with the MongoDB adapter: * MONGODB_URI=… PAYLOAD_SECRET=… node --import tsx scripts/transfer-content.ts export [--no-submissions] [--media-dir media] * import — writes through the site's config (PostgreSQL); refuses a non-empty target: * DATABASE_URI=… PAYLOAD_SECRET=… node --import tsx scripts/transfer-content.ts import * * The bundle holds every global and collection except users (the admin is * re-created by deploy.sh), the published state in both locales, open drafts, * and the upload files. It contains personal data (contact submissions) unless * exported with --no-submissions: keep it out of git, chmod 600. */ import fs from 'fs' import path from 'path' import { buildConfig, commitTransaction, createLocalReq, getPayload, initTransaction, killTransaction, type CollectionConfig, type Payload, type PayloadRequest, } from 'payload' import { mongooseAdapter } from '@payloadcms/db-mongodb' import { sharedConfig } from '../src/payload.shared' import { bundleCounts, localeData, upgradeDoc, type BundleDoc, type IdMap, type TransferBundle } from '../src/lib/content-transfer' type Data = Record type Slug = Parameters[0]['collection'] type GlobalSlug = Parameters[0]['slug'] const [mode, bundlePath, ...flags] = process.argv.slice(2) const flag = (name: string) => flags.includes(name) const option = (name: string, fallback: string) => { const i = flags.indexOf(name) return i >= 0 && flags[i + 1] ? flags[i + 1] : fallback } const collections = (sharedConfig.collections ?? []).filter((c) => c.slug !== 'users') const globals = sharedConfig.globals ?? [] const hasDrafts = (c: { versions?: unknown }) => typeof c.versions === 'object' && c.versions !== null && 'drafts' in c.versions && Boolean((c.versions as { drafts?: unknown }).drafts) const LOCALES = ['hu', 'en'] as const async function exportBundle(file: string) { const config = buildConfig({ ...sharedConfig, db: mongooseAdapter({ url: process.env.MONGODB_URI || '' }) }) const payload = await getPayload({ config }) const mediaDir = path.resolve(option('--media-dir', 'media')) const bundle: TransferBundle = { exportedAt: new Date().toISOString(), source: 'mongodb', globals: {}, collections: {}, files: {} } for (const g of globals) { const slug = g.slug as GlobalSlug const published = (await payload.findGlobal({ slug, locale: 'all', depth: 0 })) as unknown as Data const latest = (await payload.findGlobal({ slug, locale: 'all', depth: 0, draft: true })) as unknown as Data bundle.globals[slug] = { published, ...(hasDrafts(g) && latest._status === 'draft' ? { draft: latest } : {}) } } for (const c of collections) { if (c.slug === 'contact-submissions' && flag('--no-submissions')) continue const slug = c.slug as Slug const published = (await payload.find({ collection: slug, locale: 'all', depth: 0, pagination: false })).docs as unknown as Data[] const latest = hasDrafts(c) ? ((await payload.find({ collection: slug, locale: 'all', depth: 0, pagination: false, draft: true })).docs as unknown as Data[]) : [] const byId = new Map(published.map((doc) => [String(doc.id), { published: doc }])) for (const doc of latest) { const entry = byId.get(String(doc.id)) if (doc._status !== 'draft') continue if (entry) entry.draft = doc else byId.set(String(doc.id), { published: { ...doc }, draft: doc }) // never published } bundle.collections[slug] = [...byId.values()] if (c.upload) { for (const { published: doc } of bundle.collections[slug]) { const name = String(doc.filename) bundle.files[name] = { mimeType: String(doc.mimeType), base64: fs.readFileSync(path.join(mediaDir, name)).toString('base64') } } } } fs.writeFileSync(file, JSON.stringify(bundle, null, 2), { mode: 0o600 }) payload.logger.info(`MITHOME-136 export: ${JSON.stringify(bundleCounts(bundle))} → ${file}`) } async function assertEmptyTarget(payload: Payload) { for (const c of collections) { const { totalDocs } = await payload.count({ collection: c.slug as Slug }) if (totalDocs > 0) throw new Error(`Target is not empty: ${c.slug} has ${totalDocs} document(s). Nothing was written.`) } } async function importCollection(payload: Payload, req: PayloadRequest, c: CollectionConfig, docs: BundleDoc[], bundle: TransferBundle, ids: IdMap) { const slug = c.slug as Slug const drafts = hasDrafts(c) for (const raw of docs) { const entry: BundleDoc = { published: upgradeDoc(c.slug, raw.published), ...(raw.draft ? { draft: upgradeDoc(c.slug, raw.draft) } : {}) } const oldId = String(entry.published.id) const neverPublished = entry.published._status === 'draft' const status = drafts ? { _status: neverPublished ? 'draft' : 'published' } : {} const file = c.upload ? (() => { const name = String(entry.published.filename) const stored = bundle.files[name] const data = Buffer.from(stored.base64, 'base64') return { data, mimetype: stored.mimeType, name, size: data.length } })() : undefined const created = await payload.create({ req, collection: slug, locale: 'hu', data: { ...localeData(c.fields, entry.published, 'hu', ids), ...status } as never, ...(file ? { file, overwriteExistingFiles: true } : {}), draft: neverPublished, }) ids.set(oldId, String(created.id)) await payload.update({ req, collection: slug, id: created.id, locale: 'en', data: { ...localeData(c.fields, entry.published, 'en', ids), ...status } as never, draft: neverPublished, }) if (entry.draft && !neverPublished) { for (const locale of LOCALES) { await payload.update({ req, collection: slug, id: created.id, locale, draft: true, data: localeData(c.fields, entry.draft, locale, ids) as never }) } } } } async function importBundle(file: string) { const bundle = JSON.parse(fs.readFileSync(file, 'utf8')) as TransferBundle const { default: config } = await import('../src/payload.config') const payload = await getPayload({ config }) await assertEmptyTarget(payload) // One transaction: a failure leaves the target untouched ("change nothing"). const req = await createLocalReq({}, payload) await initTransaction(req) try { const ids: IdMap = new Map() // Uploads first, so relationships can be mapped to the new ids. const ordered = [...collections].sort((a, b) => Number(Boolean(b.upload)) - Number(Boolean(a.upload))) for (const c of ordered) { await importCollection(payload, req, c, bundle.collections[c.slug] ?? [], bundle, ids) } for (const g of globals) { const raw = bundle.globals[g.slug] if (!raw) continue const entry: BundleDoc = { published: upgradeDoc(g.slug, raw.published), ...(raw.draft ? { draft: upgradeDoc(g.slug, raw.draft) } : {}) } const slug = g.slug as GlobalSlug const status = hasDrafts(g) ? { _status: 'published' } : {} for (const locale of LOCALES) { await payload.updateGlobal({ req, slug, locale, data: { ...localeData(g.fields, entry.published, locale, ids), ...status } as never }) } if (entry.draft) { for (const locale of LOCALES) { await payload.updateGlobal({ req, slug, locale, draft: true, data: localeData(g.fields, entry.draft, locale, ids) as never }) } } } await commitTransaction(req) } catch (error) { await killTransaction(req) throw error } const counts: Record = {} for (const c of collections) counts[c.slug] = (await payload.count({ collection: c.slug as Slug })).totalDocs payload.logger.info(`MITHOME-136 import: expected ${JSON.stringify(bundleCounts(bundle))}, got ${JSON.stringify(counts)}`) } async function main() { if (!bundlePath || (mode !== 'export' && mode !== 'import')) { console.error('Usage: transfer-content.ts export|import [--no-submissions] [--media-dir DIR]') process.exit(2) } if (mode === 'export') await exportBundle(bundlePath) else await importBundle(bundlePath) process.exit(0) } main().catch((error) => { // Payload validation errors carry the failing fields in data.errors. const details = (error as { data?: { collection?: string; errors?: unknown } })?.data console.error('MITHOME-136 transfer failed:', error instanceof Error ? error.message : error) if (details) console.error(JSON.stringify(details, null, 2)) process.exit(1) })