feat(cms): switch Payload to PostgreSQL with a fresh baseline migration (MITHOME-136)
- postgresAdapter (uuid ids, no push, prodMigrations), DATABASE_URI - src/payload.shared.ts: the config without the db adapter, shared with the one-off MongoDB content transfer - baseline migration 20260929_200306_initial (86 tables; applied twice on a disposable PostgreSQL 16: second run is a no-op) - seed copy (references, hosting plans) moved to src/content/seeds/ - MongoDB data migrations, their helpers/tests and the dead lib/mongodb.ts removed (kept in git history) - npm scripts for the Payload CLI (works now that the package is ESM) Branch only: staging has no PostgreSQL yet (tasks 3.x). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a3d6cbe404
commit
e3ec6a9ac3
@@ -1,105 +0,0 @@
|
||||
import { reviseContent, type ListInsertion, type TextRevision } from './content-revision'
|
||||
import { collectLocalizedPaths } from './localize-paths'
|
||||
|
||||
type Doc = Record<string, unknown>
|
||||
|
||||
const FIELDS = [
|
||||
{ name: 'title', type: 'text', localized: true },
|
||||
{ name: 'items', type: 'array', localized: true, fields: [{ name: 'value', type: 'text' }] },
|
||||
]
|
||||
const PATHS = collectLocalizedPaths(FIELDS)
|
||||
|
||||
const REVISIONS: TextRevision[] = [
|
||||
{ from: 'Régi cím', to: 'Új cím', enWas: 'Old title', enTo: 'New title' },
|
||||
{ from: 'Régi elem', to: 'Új elem', enWas: 'Old item', enTo: 'New item' },
|
||||
]
|
||||
const INSERTIONS: ListInsertion[] = [{ afterHu: 'Új elem', hu: 'Beszúrt', afterEn: 'New item', en: 'Inserted' }]
|
||||
|
||||
let seq = 0
|
||||
const newId = () => `id-${++seq}`
|
||||
beforeEach(() => {
|
||||
seq = 0
|
||||
})
|
||||
|
||||
const doc = (): Doc => ({
|
||||
title: { hu: 'Régi cím', en: 'Old title' },
|
||||
items: {
|
||||
hu: [{ value: 'Régi elem', id: 'h1' }, { value: 'Marad', id: 'h2' }],
|
||||
en: [{ value: 'Old item', id: 'e1' }, { value: 'Stays', id: 'e2' }],
|
||||
},
|
||||
enTranslationStatus: 'ai-draft',
|
||||
})
|
||||
|
||||
describe('reviseContent (MITHOME-129)', () => {
|
||||
it('should replace exact Hungarian matches and their AI-draft English', () => {
|
||||
const d = doc()
|
||||
const report = reviseContent(d, PATHS, REVISIONS, [], newId)
|
||||
expect(d.title).toEqual({ hu: 'Új cím', en: 'New title' })
|
||||
expect(d.items).toEqual({
|
||||
hu: [{ value: 'Új elem', id: 'h1' }, { value: 'Marad', id: 'h2' }],
|
||||
en: [{ value: 'New item', id: 'e1' }, { value: 'Stays', id: 'e2' }],
|
||||
})
|
||||
expect(report).toEqual({ changed: 2, enKept: [] })
|
||||
})
|
||||
|
||||
it('should leave text an editor already rewrote untouched', () => {
|
||||
const d: Doc = { title: { hu: 'Szerkesztett cím', en: 'Edited title' } }
|
||||
expect(reviseContent(d, PATHS, REVISIONS, [], newId)).toEqual({ changed: 0, enKept: [] })
|
||||
expect(d.title).toEqual({ hu: 'Szerkesztett cím', en: 'Edited title' })
|
||||
})
|
||||
|
||||
it('should keep and report a human English edit', () => {
|
||||
const d: Doc = { title: { hu: 'Régi cím', en: 'Human title' } }
|
||||
const report = reviseContent(d, PATHS, REVISIONS, [], newId)
|
||||
expect(d.title).toEqual({ hu: 'Új cím', en: 'Human title' })
|
||||
expect(report.enKept).toEqual(['Régi cím'])
|
||||
})
|
||||
|
||||
it('should report a list item whose English row was edited by a person', () => {
|
||||
const d = doc()
|
||||
;(d.items as { en: { value: string }[] }).en[0].value = 'Human item'
|
||||
const report = reviseContent(d, PATHS, REVISIONS, [], newId)
|
||||
expect(report.enKept).toEqual(['Régi elem'])
|
||||
expect((d.items as { en: { value: string }[] }).en[0].value).toBe('Human item')
|
||||
})
|
||||
|
||||
it('should fill an empty English value', () => {
|
||||
const d: Doc = { title: { hu: 'Régi cím' } }
|
||||
reviseContent(d, PATHS, REVISIONS, [], newId)
|
||||
expect(d.title).toEqual({ hu: 'Új cím', en: 'New title' })
|
||||
})
|
||||
|
||||
it('should insert a list item after its anchor in both languages, once', () => {
|
||||
const d = doc()
|
||||
reviseContent(d, PATHS, REVISIONS, INSERTIONS, newId)
|
||||
reviseContent(d, PATHS, REVISIONS, INSERTIONS, newId)
|
||||
const items = d.items as { hu: { value: string }[]; en: { value: string }[] }
|
||||
expect(items.hu.map((r) => r.value)).toEqual(['Új elem', 'Beszúrt', 'Marad'])
|
||||
expect(items.en.map((r) => r.value)).toEqual(['New item', 'Inserted', 'Stays'])
|
||||
})
|
||||
|
||||
it('should be idempotent', () => {
|
||||
const d = doc()
|
||||
reviseContent(d, PATHS, REVISIONS, INSERTIONS, newId)
|
||||
const snapshot = JSON.stringify(d)
|
||||
expect(reviseContent(d, PATHS, REVISIONS, INSERTIONS, newId)).toEqual({ changed: 0, enKept: [] })
|
||||
expect(JSON.stringify(d)).toBe(snapshot)
|
||||
})
|
||||
|
||||
it('should send an approved page back to AI draft when its English changed', () => {
|
||||
const d = { ...doc(), enTranslationStatus: 'approved' }
|
||||
reviseContent(d, PATHS, REVISIONS, [], newId)
|
||||
expect(d.enTranslationStatus).toBe('ai-draft')
|
||||
})
|
||||
|
||||
it('should keep an approved status when only Hungarian changed', () => {
|
||||
const d: Doc = { title: { hu: 'Régi cím', en: 'Human title' }, enTranslationStatus: 'approved' }
|
||||
reviseContent(d, PATHS, REVISIONS, [], newId)
|
||||
expect(d.enTranslationStatus).toBe('approved')
|
||||
})
|
||||
|
||||
it('should ignore legacy unwrapped values and lists without an anchor', () => {
|
||||
const d: Doc = { title: 'Régi cím', items: { hu: [{ value: 'Más', id: 'x' }] } }
|
||||
expect(reviseContent(d, PATHS, REVISIONS, INSERTIONS, newId)).toEqual({ changed: 0, enKept: [] })
|
||||
})
|
||||
})
|
||||
@@ -1,96 +0,0 @@
|
||||
/**
|
||||
* MITHOME-129: exact-match content revision on localized fields, in place.
|
||||
*
|
||||
* Used by data migrations that correct published copy (e.g. service claims
|
||||
* aligned with the real product range). Rules:
|
||||
* - a value changes only when its current Hungarian text is EXACTLY the
|
||||
* expected old text — anything an editor already rewrote is left alone;
|
||||
* - English is replaced only when it is empty or still the old AI draft
|
||||
* (`enWas`) — a human English edit is kept and reported instead;
|
||||
* - if English changed on a page whose translation was approved, the page
|
||||
* goes back to "ai-draft": the new English has not been reviewed yet.
|
||||
* Works for localized text leaves and whole-array localized string lists
|
||||
* ({ value } rows), where it can also insert a new item after an anchor.
|
||||
*/
|
||||
import { applyAll, isPlainObject, type LocalizedPath } from './localize-paths'
|
||||
|
||||
export type TextRevision = { from: string; to: string; enWas?: string; enTo: string }
|
||||
export type ListInsertion = { afterHu: string; hu: string; afterEn: string; en: string }
|
||||
export type RevisionReport = { changed: number; enKept: string[] }
|
||||
|
||||
type Row = { value?: unknown; id?: unknown }
|
||||
|
||||
const isEmpty = (value: unknown) => value === undefined || value === null || value === ''
|
||||
|
||||
function reviseText(value: Record<string, unknown>, revisions: readonly TextRevision[], report: RevisionReport) {
|
||||
const revision = revisions.find((r) => r.from === value.hu)
|
||||
if (!revision) return { hu: false, en: false }
|
||||
value.hu = revision.to
|
||||
if (isEmpty(value.en) || value.en === revision.enWas) {
|
||||
value.en = revision.enTo
|
||||
return { hu: true, en: true }
|
||||
}
|
||||
report.enKept.push(revision.from)
|
||||
return { hu: true, en: false }
|
||||
}
|
||||
|
||||
function reviseRows(rows: Row[], match: (text: string) => string | undefined): number {
|
||||
let count = 0
|
||||
for (const row of rows) {
|
||||
const next = typeof row.value === 'string' ? match(row.value) : undefined
|
||||
if (next !== undefined) {
|
||||
row.value = next
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
function insertRow(rows: Row[], after: string, text: string, newId: () => string): boolean {
|
||||
if (rows.some((row) => row.value === text)) return false
|
||||
const index = rows.findIndex((row) => row.value === after)
|
||||
if (index === -1) return false
|
||||
rows.splice(index + 1, 0, { value: text, id: newId() })
|
||||
return true
|
||||
}
|
||||
|
||||
export function reviseContent(
|
||||
doc: Record<string, unknown>,
|
||||
paths: readonly LocalizedPath[],
|
||||
revisions: readonly TextRevision[],
|
||||
insertions: readonly ListInsertion[],
|
||||
newId: () => string,
|
||||
): RevisionReport {
|
||||
const report: RevisionReport = { changed: 0, enKept: [] }
|
||||
let enChanged = false
|
||||
|
||||
applyAll(doc, paths, (value) => {
|
||||
if (!isPlainObject(value)) return { value, changed: false }
|
||||
|
||||
if (typeof value.hu === 'string') {
|
||||
const result = reviseText(value, revisions, report)
|
||||
enChanged ||= result.en
|
||||
if (result.hu) report.changed += 1
|
||||
return { value, changed: result.hu }
|
||||
}
|
||||
|
||||
if (!Array.isArray(value.hu)) return { value, changed: false }
|
||||
const hu = value.hu as Row[]
|
||||
const en = Array.isArray(value.en) ? (value.en as Row[]) : undefined
|
||||
const huMatched = revisions.filter((r) => hu.some((row) => row.value === r.from))
|
||||
let count = reviseRows(hu, (text) => revisions.find((r) => r.from === text)?.to)
|
||||
const enCount = en ? reviseRows(en, (text) => revisions.find((r) => r.enWas !== undefined && r.enWas === text)?.enTo) : 0
|
||||
// A Hungarian row changed but its English row was not the old AI draft.
|
||||
if (en && enCount < huMatched.length) report.enKept.push(...huMatched.map((r) => r.from).slice(enCount))
|
||||
for (const insertion of insertions) {
|
||||
if (insertRow(hu, insertion.afterHu, insertion.hu, newId)) count += 1
|
||||
if (en && insertRow(en, insertion.afterEn, insertion.en, newId)) enChanged = true
|
||||
}
|
||||
enChanged ||= enCount > 0
|
||||
report.changed += count
|
||||
return { value, changed: count > 0 || enCount > 0 }
|
||||
})
|
||||
|
||||
if (enChanged && doc.enTranslationStatus === 'approved') doc.enTranslationStatus = 'ai-draft'
|
||||
return report
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
import { fillEnglishDraft } from './english-draft'
|
||||
import { collectLocalizedPaths } from './localize-paths'
|
||||
|
||||
type Doc = Record<string, unknown>
|
||||
|
||||
const FIELDS = [
|
||||
{ name: 'title', type: 'text', localized: true },
|
||||
{ name: 'paragraphs', type: 'array', localized: true, fields: [{ name: 'value', type: 'text' }] },
|
||||
{ name: 'items', type: 'array', fields: [{ name: 'icon', type: 'text' }, { name: 'label', type: 'text', localized: true }] },
|
||||
]
|
||||
const PATHS = collectLocalizedPaths(FIELDS)
|
||||
const MEMORY = { Cím: 'Title', Egy: 'One', Kettő: 'Two', Címke: 'Label' }
|
||||
|
||||
let seq = 0
|
||||
const newId = () => `new-${++seq}`
|
||||
beforeEach(() => {
|
||||
seq = 0
|
||||
})
|
||||
|
||||
const doc = (): Doc => ({
|
||||
title: { hu: 'Cím' },
|
||||
paragraphs: { hu: [{ value: 'Egy', id: 'p1' }, { value: 'Kettő', id: 'p2' }] },
|
||||
items: [{ id: 'r1', icon: 'star', label: { hu: 'Címke' } }],
|
||||
})
|
||||
|
||||
describe('fillEnglishDraft (MITHOME-113)', () => {
|
||||
it('should fill empty English values from the memory and mark the page as AI draft', () => {
|
||||
const d = doc()
|
||||
const report = fillEnglishDraft(d, PATHS, MEMORY, newId)
|
||||
|
||||
expect(report).toEqual({ filled: 3, unmatched: [] })
|
||||
expect(d.title).toEqual({ hu: 'Cím', en: 'Title' })
|
||||
expect(d.paragraphs).toEqual({
|
||||
hu: [{ value: 'Egy', id: 'p1' }, { value: 'Kettő', id: 'p2' }],
|
||||
en: [{ value: 'One', id: 'new-1' }, { value: 'Two', id: 'new-2' }],
|
||||
})
|
||||
expect(d.items).toEqual([{ id: 'r1', icon: 'star', label: { hu: 'Címke', en: 'Label' } }])
|
||||
expect(d.enTranslationStatus).toBe('ai-draft')
|
||||
})
|
||||
|
||||
it('should leave an edited Hungarian text without English and report it', () => {
|
||||
const d = doc()
|
||||
d.title = { hu: 'Új cím' }
|
||||
const report = fillEnglishDraft(d, PATHS, MEMORY, newId)
|
||||
expect(d.title).toEqual({ hu: 'Új cím' })
|
||||
expect(report.unmatched).toEqual(['Új cím'])
|
||||
})
|
||||
|
||||
it('should never overwrite an existing English value', () => {
|
||||
const d = doc()
|
||||
d.title = { hu: 'Cím', en: 'Human title' }
|
||||
fillEnglishDraft(d, PATHS, MEMORY, newId)
|
||||
expect(d.title).toEqual({ hu: 'Cím', en: 'Human title' })
|
||||
})
|
||||
|
||||
it('should not fill a list partially', () => {
|
||||
const d = doc()
|
||||
d.paragraphs = { hu: [{ value: 'Egy', id: 'p1' }, { value: 'Ismeretlen', id: 'p2' }] }
|
||||
const report = fillEnglishDraft(d, PATHS, MEMORY, newId)
|
||||
expect(d.paragraphs).not.toHaveProperty('en')
|
||||
expect(report.unmatched).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('should treat an empty English list as empty', () => {
|
||||
const d = doc()
|
||||
d.paragraphs = { hu: [{ value: 'Egy', id: 'p1' }], en: [] }
|
||||
fillEnglishDraft(d, PATHS, MEMORY, newId)
|
||||
expect((d.paragraphs as { en: unknown[] }).en).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('should be idempotent', () => {
|
||||
const d = doc()
|
||||
fillEnglishDraft(d, PATHS, MEMORY, newId)
|
||||
const snapshot = JSON.stringify(d)
|
||||
expect(fillEnglishDraft(d, PATHS, MEMORY, newId)).toEqual({ filled: 0, unmatched: [] })
|
||||
expect(JSON.stringify(d)).toBe(snapshot)
|
||||
})
|
||||
|
||||
it.each(['approved', 'ai-draft'])('should keep an existing "%s" status', (status) => {
|
||||
const d = { ...doc(), enTranslationStatus: status }
|
||||
fillEnglishDraft(d, PATHS, MEMORY, newId)
|
||||
expect(d.enTranslationStatus).toBe(status)
|
||||
})
|
||||
|
||||
it('should not change the status when nothing was filled', () => {
|
||||
const d: Doc = { title: { hu: 'Ismeretlen' }, enTranslationStatus: 'none' }
|
||||
fillEnglishDraft(d, PATHS, MEMORY, newId)
|
||||
expect(d.enTranslationStatus).toBe('none')
|
||||
})
|
||||
|
||||
it('should skip empty Hungarian values and legacy (unwrapped) strings', () => {
|
||||
const d: Doc = { title: 'Cím', paragraphs: { hu: [] } }
|
||||
expect(fillEnglishDraft(d, PATHS, MEMORY, newId)).toEqual({ filled: 0, unmatched: [] })
|
||||
})
|
||||
})
|
||||
@@ -1,54 +0,0 @@
|
||||
/**
|
||||
* MITHOME-113: fills empty English values from the hu -> en translation
|
||||
* memory (src/content/translations/en.json), in place.
|
||||
*
|
||||
* Rules (design D5):
|
||||
* - only an EMPTY `en` is filled — human English edits are never touched;
|
||||
* - only when the current `hu` text is EXACTLY a memory key — a Hungarian
|
||||
* text edited after translation gets no (stale) English;
|
||||
* - a whole-array localized list is filled all-or-nothing, so a list is
|
||||
* never half English;
|
||||
* - `enTranslationStatus` goes none -> ai-draft when something was filled;
|
||||
* "approved" is never set here.
|
||||
*/
|
||||
import { applyAll, isPlainObject, type LocalizedPath } from './localize-paths'
|
||||
|
||||
type Row = { value?: unknown; id?: unknown }
|
||||
export type DraftReport = { filled: number; unmatched: string[] }
|
||||
|
||||
const isEmpty = (value: unknown) =>
|
||||
value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0)
|
||||
|
||||
function translateList(rows: Row[], memory: Record<string, string>, newId: () => string): Row[] | undefined {
|
||||
const values = rows.map((row) => row.value)
|
||||
if (!values.every((v): v is string => typeof v === 'string' && v in memory)) return undefined
|
||||
return values.map((v) => ({ value: memory[v], id: newId() }))
|
||||
}
|
||||
|
||||
export function fillEnglishDraft(
|
||||
doc: Record<string, unknown>,
|
||||
paths: readonly LocalizedPath[],
|
||||
memory: Record<string, string>,
|
||||
newId: () => string,
|
||||
): DraftReport {
|
||||
const report: DraftReport = { filled: 0, unmatched: [] }
|
||||
|
||||
applyAll(doc, paths, (value) => {
|
||||
if (!isPlainObject(value) || !isEmpty(value.en) || isEmpty(value.hu)) return { value, changed: false }
|
||||
const hu = value.hu
|
||||
const en =
|
||||
typeof hu === 'string' ? memory[hu] : Array.isArray(hu) ? translateList(hu as Row[], memory, newId) : undefined
|
||||
if (en === undefined) {
|
||||
report.unmatched.push(typeof hu === 'string' ? hu : JSON.stringify(hu))
|
||||
return { value, changed: false }
|
||||
}
|
||||
value.en = en
|
||||
report.filled += 1
|
||||
return { value, changed: true }
|
||||
})
|
||||
|
||||
if (report.filled > 0 && (isEmpty(doc.enTranslationStatus) || doc.enTranslationStatus === 'none')) {
|
||||
doc.enTranslationStatus = 'ai-draft'
|
||||
}
|
||||
return report
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
import { collectLocalizedPaths, topLevelKeys, unwrapLocalized, wrapLocalized } from './localize-paths'
|
||||
import { Home } from '../globals/Home'
|
||||
import { Common } from '../globals/Common'
|
||||
|
||||
type Doc = Record<string, unknown>
|
||||
|
||||
const FIELDS = [
|
||||
{
|
||||
name: 'hero',
|
||||
type: 'group',
|
||||
fields: [
|
||||
{ name: 'title', type: 'text', localized: true },
|
||||
{ name: 'bullets', type: 'array', localized: true, fields: [{ name: 'value', type: 'text' }] },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'items',
|
||||
type: 'array',
|
||||
fields: [
|
||||
{ name: 'icon', type: 'text' },
|
||||
{ name: 'title', type: 'text', localized: true },
|
||||
{ name: 'features', type: 'array', localized: true, fields: [{ name: 'value', type: 'text' }] },
|
||||
],
|
||||
},
|
||||
{ name: 'address', type: 'text' },
|
||||
{ name: 'external', type: 'checkbox' },
|
||||
]
|
||||
|
||||
function legacyDoc(): Doc {
|
||||
return {
|
||||
hero: { title: 'Cím', bullets: [{ id: 'b1', value: 'Egy' }] },
|
||||
items: [
|
||||
{ id: 'r1', icon: 'star', title: 'Első', features: [{ id: 'f1', value: 'A' }] },
|
||||
{ id: 'r2', icon: 'bolt', title: 'Második', features: [] },
|
||||
],
|
||||
address: 'Budapest',
|
||||
external: false,
|
||||
}
|
||||
}
|
||||
|
||||
describe('collectLocalizedPaths', () => {
|
||||
it('should collect localized leaves through groups and shared array rows', () => {
|
||||
expect(collectLocalizedPaths(FIELDS)).toEqual([
|
||||
['hero', 'title'],
|
||||
['hero', 'bullets'],
|
||||
['items', '[]', 'title'],
|
||||
['items', '[]', 'features'],
|
||||
])
|
||||
})
|
||||
|
||||
it('should look through unnamed row/collapsible wrappers', () => {
|
||||
expect(
|
||||
collectLocalizedPaths([
|
||||
{ name: 'g', type: 'group', fields: [{ type: 'row', fields: [{ name: 't', type: 'text', localized: true }] }] },
|
||||
{ type: 'collapsible', fields: [{ name: 'u', type: 'text', localized: true }] },
|
||||
]),
|
||||
).toEqual([['g', 't'], ['u']])
|
||||
})
|
||||
|
||||
it('should throw on layout fields that could hide localized data', () => {
|
||||
expect(() => collectLocalizedPaths([{ type: 'tabs' }])).toThrow('unsupported field type "tabs"')
|
||||
})
|
||||
|
||||
it('should derive paths from the real Global configs', () => {
|
||||
const homePaths = collectLocalizedPaths(Home.fields as never)
|
||||
expect(homePaths).toContainEqual(['hero', 'trustBullets'])
|
||||
expect(homePaths).toContainEqual(['services', 'items', '[]', 'features'])
|
||||
expect(homePaths).not.toContainEqual(['about', 'usps', '[]', 'icon'])
|
||||
expect(collectLocalizedPaths(Common.fields as never)).not.toContainEqual(['footer', 'address'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('wrapLocalized', () => {
|
||||
const paths = collectLocalizedPaths(FIELDS)
|
||||
|
||||
it('should wrap strings and arrays under the hu locale and keep shared values', () => {
|
||||
const doc = legacyDoc()
|
||||
const changed = wrapLocalized(doc, paths)
|
||||
|
||||
expect(changed).toBe(6)
|
||||
expect(doc.hero).toEqual({ title: { hu: 'Cím' }, bullets: { hu: [{ id: 'b1', value: 'Egy' }] } })
|
||||
expect(doc.items).toEqual([
|
||||
{ id: 'r1', icon: 'star', title: { hu: 'Első' }, features: { hu: [{ id: 'f1', value: 'A' }] } },
|
||||
{ id: 'r2', icon: 'bolt', title: { hu: 'Második' }, features: { hu: [] } },
|
||||
])
|
||||
expect(doc.address).toBe('Budapest')
|
||||
expect(doc.external).toBe(false)
|
||||
})
|
||||
|
||||
it('should be idempotent on already migrated data', () => {
|
||||
const doc = legacyDoc()
|
||||
wrapLocalized(doc, paths)
|
||||
const snapshot = JSON.stringify(doc)
|
||||
|
||||
expect(wrapLocalized(doc, paths)).toBe(0)
|
||||
expect(JSON.stringify(doc)).toBe(snapshot)
|
||||
})
|
||||
|
||||
it('should leave existing locale maps (e.g. Common.buttons) untouched', () => {
|
||||
const doc: Doc = { hero: { title: { hu: 'Cím', en: 'Title' } } }
|
||||
expect(wrapLocalized(doc, paths)).toBe(0)
|
||||
expect(doc).toEqual({ hero: { title: { hu: 'Cím', en: 'Title' } } })
|
||||
})
|
||||
|
||||
it('should skip missing branches and null values', () => {
|
||||
const doc: Doc = { hero: { title: null }, items: null }
|
||||
expect(wrapLocalized(doc, paths)).toBe(0)
|
||||
expect(doc).toEqual({ hero: { title: null }, items: null })
|
||||
})
|
||||
|
||||
it('should not descend into a row path when the stored value is not an array', () => {
|
||||
const doc: Doc = { items: { unexpected: true } }
|
||||
expect(wrapLocalized(doc, paths)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('unwrapLocalized', () => {
|
||||
const paths = collectLocalizedPaths(FIELDS)
|
||||
|
||||
it('should restore the legacy shape from the hu value', () => {
|
||||
const doc = legacyDoc()
|
||||
wrapLocalized(doc, paths)
|
||||
;(doc.hero as Doc).title = { hu: 'Cím', en: 'Title' }
|
||||
|
||||
expect(unwrapLocalized(doc, paths)).toBe(6)
|
||||
expect(doc).toEqual(legacyDoc())
|
||||
})
|
||||
|
||||
it('should fall back to null when the hu value is missing', () => {
|
||||
const doc: Doc = { hero: { title: { en: 'Title' } } }
|
||||
unwrapLocalized(doc, paths)
|
||||
expect(doc).toEqual({ hero: { title: null } })
|
||||
})
|
||||
})
|
||||
|
||||
describe('topLevelKeys', () => {
|
||||
it('should return unique first segments', () => {
|
||||
expect(topLevelKeys(collectLocalizedPaths(FIELDS))).toEqual(['hero', 'items'])
|
||||
})
|
||||
})
|
||||
@@ -1,119 +0,0 @@
|
||||
/**
|
||||
* MITHOME-111: pure helpers for the "field became `localized: true`"
|
||||
* data migration (design D4).
|
||||
*
|
||||
* WHY config-driven paths: the Global configs are the single source of
|
||||
* truth for which fields are localized — deriving the migration paths from
|
||||
* them means the migration can never drift from the schema.
|
||||
*
|
||||
* Storage shapes (Payload mongooseAdapter):
|
||||
* non-localized text -> "szöveg" localized -> { hu: "szöveg" }
|
||||
* non-localized array -> [{ value }] localized -> { hu: [{ value }] }
|
||||
* A path segment `[]` means "every row of this (shared) array".
|
||||
*/
|
||||
|
||||
type FieldNode = { name?: string; type: string; localized?: boolean; fields?: FieldNode[] }
|
||||
|
||||
export type LocalizedPath = readonly string[]
|
||||
|
||||
const ARRAY_ROWS = '[]'
|
||||
|
||||
/** Layout fields that could hide localized children — not traversed here. */
|
||||
const UNSUPPORTED_CONTAINERS = new Set(['tabs', 'blocks'])
|
||||
|
||||
/** Unnamed layout wrappers: their children are stored at the same level. */
|
||||
const TRANSPARENT_CONTAINERS = new Set(['row', 'collapsible'])
|
||||
|
||||
export function collectLocalizedPaths(
|
||||
fields: readonly FieldNode[],
|
||||
prefix: LocalizedPath = [],
|
||||
): LocalizedPath[] {
|
||||
const paths: LocalizedPath[] = []
|
||||
for (const field of fields) {
|
||||
if (UNSUPPORTED_CONTAINERS.has(field.type)) {
|
||||
// DECISION: fail fast rather than silently skip localized data.
|
||||
throw new Error(`collectLocalizedPaths: unsupported field type "${field.type}"`)
|
||||
}
|
||||
if (TRANSPARENT_CONTAINERS.has(field.type)) {
|
||||
paths.push(...collectLocalizedPaths(field.fields ?? [], prefix))
|
||||
continue
|
||||
}
|
||||
if (!field.name) continue
|
||||
const path = [...prefix, field.name]
|
||||
if (field.localized) {
|
||||
paths.push(path)
|
||||
} else if (field.type === 'group') {
|
||||
paths.push(...collectLocalizedPaths(field.fields ?? [], path))
|
||||
} else if (field.type === 'array') {
|
||||
paths.push(...collectLocalizedPaths(field.fields ?? [], [...path, ARRAY_ROWS]))
|
||||
}
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
export type Transform = (value: unknown) => { value: unknown; changed: boolean }
|
||||
|
||||
export function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function applyAtPath(node: unknown, path: LocalizedPath, transform: Transform): number {
|
||||
if (typeof node !== 'object' || node === null) return 0
|
||||
const [head, ...rest] = path
|
||||
if (head === ARRAY_ROWS) {
|
||||
if (!Array.isArray(node)) return 0
|
||||
return node.reduce<number>((sum, row) => sum + applyAtPath(row, rest, transform), 0)
|
||||
}
|
||||
if (!isPlainObject(node)) return 0
|
||||
if (rest.length > 0) return applyAtPath(node[head], rest, transform)
|
||||
|
||||
const result = transform(node[head])
|
||||
if (result.changed) node[head] = result.value
|
||||
return result.changed ? 1 : 0
|
||||
}
|
||||
|
||||
// WHY in-place mutation instead of structuredClone: raw Mongo documents
|
||||
// carry BSON class instances (ObjectId) that a structured clone would
|
||||
// silently turn into plain objects. Callers pass freshly read documents.
|
||||
/** Applies `transform` to every value at `paths`, in place; returns the change count. */
|
||||
export function applyAll(doc: Record<string, unknown>, paths: readonly LocalizedPath[], transform: Transform) {
|
||||
return paths.reduce((sum, path) => sum + applyAtPath(doc, path, transform), 0)
|
||||
}
|
||||
|
||||
/** Top-level document keys touched by `paths` — the `$set` scope of a write. */
|
||||
export function topLevelKeys(paths: readonly LocalizedPath[]): string[] {
|
||||
return [...new Set(paths.map((path) => path[0]))]
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps legacy (non-localized) values into `{ [locale]: value }`, in place.
|
||||
* Idempotent: values already stored as a locale map are left untouched,
|
||||
* null/undefined are skipped (nothing to preserve). Returns the number of
|
||||
* values changed.
|
||||
*/
|
||||
export function wrapLocalized(
|
||||
doc: Record<string, unknown>,
|
||||
paths: readonly LocalizedPath[],
|
||||
locale = 'hu',
|
||||
) {
|
||||
return applyAll(doc, paths, (value) =>
|
||||
typeof value === 'string' || Array.isArray(value)
|
||||
? { value: { [locale]: value }, changed: true }
|
||||
: { value, changed: false },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Inverse of wrapLocalized (down migration), in place: keeps only
|
||||
* `locale`'s value.
|
||||
* TRADEOFF: every other locale's value is dropped — take a DB dump first.
|
||||
*/
|
||||
export function unwrapLocalized(
|
||||
doc: Record<string, unknown>,
|
||||
paths: readonly LocalizedPath[],
|
||||
locale = 'hu',
|
||||
) {
|
||||
return applyAll(doc, paths, (value) =>
|
||||
isPlainObject(value) ? { value: value[locale] ?? null, changed: true } : { value, changed: false },
|
||||
)
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
/**
|
||||
* Shared plumbing for Payload data migrations (MITHOME-111/112/113/123).
|
||||
*
|
||||
* Applies `transform` in place to a global's or collection's field data —
|
||||
* the stored document(s) AND the draft/version records (`version`
|
||||
* sub-document) — and writes back only what changed.
|
||||
*
|
||||
* DECISION: direct Mongo `updateOne` instead of the Local API — no new
|
||||
* version is created, no hooks run, `updatedAt` stays untouched.
|
||||
*/
|
||||
import type { MigrateDownArgs, MigrateUpArgs, MongooseAdapter } from '@payloadcms/db-mongodb'
|
||||
|
||||
type Args = MigrateUpArgs | MigrateDownArgs
|
||||
type Data = Record<string, unknown>
|
||||
|
||||
export type DocTarget = { kind: 'global' | 'collection'; slug: string }
|
||||
|
||||
type RewriteOptions = {
|
||||
/**
|
||||
* 'all' rewrites the whole history (shape changes must reach every
|
||||
* version); 'latest' only the working copy the admin form loads (content
|
||||
* imports should not rewrite history).
|
||||
*/
|
||||
versions?: 'all' | 'latest'
|
||||
}
|
||||
|
||||
function pick(doc: Data, keys: readonly string[]) {
|
||||
return Object.fromEntries(keys.filter((key) => key in doc).map((key) => [key, doc[key]]))
|
||||
}
|
||||
|
||||
/**
|
||||
* @param keys top-level field names `transform` may touch (the `$set` scope)
|
||||
* @returns the number of values `transform` reported as changed
|
||||
*/
|
||||
export async function rewriteDocs(
|
||||
{ payload, session }: Args,
|
||||
target: DocTarget,
|
||||
keys: readonly string[],
|
||||
transform: (data: Data) => number,
|
||||
{ versions: scope = 'all' }: RewriteOptions = {},
|
||||
): Promise<number> {
|
||||
const db = payload.db as unknown as MongooseAdapter
|
||||
let changed = 0
|
||||
|
||||
const main =
|
||||
target.kind === 'global' ? db.globals.collection : db.collections[target.slug]?.collection
|
||||
const mainFilter = target.kind === 'global' ? { globalType: target.slug } : {}
|
||||
if (main) {
|
||||
for await (const doc of main.find(mainFilter, { session })) {
|
||||
const count = transform(doc)
|
||||
if (count > 0) {
|
||||
await main.updateOne({ _id: doc._id }, { $set: pick(doc, keys) }, { session })
|
||||
changed += count
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const versions = db.versions[target.slug]
|
||||
if (versions) {
|
||||
const filter = scope === 'latest' ? { latest: true } : {}
|
||||
for await (const doc of versions.collection.find(filter, { session })) {
|
||||
if (typeof doc.version !== 'object' || doc.version === null) continue
|
||||
const count = transform(doc.version)
|
||||
if (count > 0) {
|
||||
await versions.collection.updateOne({ _id: doc._id }, { $set: { version: doc.version } }, { session })
|
||||
changed += count
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return changed
|
||||
}
|
||||
|
||||
/** Global shorthand kept for the MITHOME-111/123 migrations. */
|
||||
export function rewriteGlobalDocs(
|
||||
args: Args,
|
||||
slug: string,
|
||||
keys: readonly string[],
|
||||
transform: (data: Data) => number,
|
||||
): Promise<number> {
|
||||
return rewriteDocs(args, { kind: 'global', slug }, keys, transform)
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
// Mock the MongoDB module completely
|
||||
const mockDb = {
|
||||
collection: jest.fn().mockReturnValue({
|
||||
findOne: jest.fn(),
|
||||
insertOne: jest.fn(),
|
||||
updateOne: jest.fn(),
|
||||
deleteOne: jest.fn()
|
||||
}),
|
||||
admin: jest.fn().mockReturnValue({
|
||||
ping: jest.fn().mockResolvedValue(true)
|
||||
})
|
||||
}
|
||||
|
||||
const mockClient = {
|
||||
connect: jest.fn(),
|
||||
close: jest.fn().mockResolvedValue(undefined),
|
||||
db: jest.fn().mockReturnValue(mockDb)
|
||||
}
|
||||
|
||||
const mockMongoLoggerError = jest.fn()
|
||||
|
||||
jest.mock('./logger', () => ({
|
||||
dbLogger: { error: mockMongoLoggerError },
|
||||
getSafeErrorDetails: (error: unknown) => ({
|
||||
errorName: error instanceof Error ? error.name : 'Error'
|
||||
})
|
||||
}))
|
||||
|
||||
// The connect method should resolve to the client itself
|
||||
mockClient.connect.mockResolvedValue(mockClient)
|
||||
|
||||
const MockedMongoClient = jest.fn().mockImplementation(() => mockClient)
|
||||
|
||||
// Mock the mongodb module
|
||||
jest.mock('mongodb', () => ({
|
||||
MongoClient: MockedMongoClient
|
||||
}))
|
||||
|
||||
// Restore environment before tests
|
||||
const originalEnv = process.env
|
||||
|
||||
describe('MongoDB Connection (Unit Tests)', () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules()
|
||||
process.env = {
|
||||
...originalEnv,
|
||||
MONGODB_URI: 'mongodb://localhost:27017/test',
|
||||
MONGODB_DB: 'test'
|
||||
}
|
||||
jest.clearAllMocks()
|
||||
mockMongoLoggerError.mockReset()
|
||||
|
||||
// Reset the mock implementation
|
||||
MockedMongoClient.mockImplementation(() => mockClient as any)
|
||||
mockClient.db.mockReturnValue(mockDb)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
process.env = originalEnv
|
||||
})
|
||||
|
||||
describe('MongoDB URI validation', () => {
|
||||
it('should throw error when MONGODB_URI is not set', () => {
|
||||
// This test is tricky because the module is cached
|
||||
// We'll test this by clearing the module cache and mocking process.env
|
||||
const originalMongodbUri = process.env.MONGODB_URI
|
||||
delete process.env.MONGODB_URI
|
||||
|
||||
// Clear module cache to force re-import
|
||||
jest.resetModules()
|
||||
|
||||
const { getClientPromise } = require('./mongodb')
|
||||
expect(() => getClientPromise()).toThrow('Please add MONGODB_URI to your environment variables')
|
||||
|
||||
// Restore environment
|
||||
process.env.MONGODB_URI = originalMongodbUri
|
||||
})
|
||||
})
|
||||
|
||||
describe('Database connection', () => {
|
||||
it('should create MongoClient with correct URI and options', async () => {
|
||||
// Import after setting up the mock
|
||||
const { getClientPromise } = await import('./mongodb')
|
||||
|
||||
await getClientPromise()
|
||||
|
||||
expect(MockedMongoClient).toHaveBeenCalledWith(
|
||||
process.env.MONGODB_URI,
|
||||
expect.objectContaining({
|
||||
maxPoolSize: 10,
|
||||
serverSelectionTimeoutMS: 5000,
|
||||
socketTimeoutMS: 45000
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('should return database instance', async () => {
|
||||
const { getDb } = await import('./mongodb')
|
||||
|
||||
const result = await getDb()
|
||||
|
||||
expect(result).toBe(mockDb)
|
||||
expect(typeof result.collection).toBe('function')
|
||||
})
|
||||
|
||||
it('should check MongoDB connection successfully', async () => {
|
||||
const { checkMongoConnection } = await import('./mongodb')
|
||||
|
||||
const result = await checkMongoConnection()
|
||||
expect(result).toBe(true)
|
||||
})
|
||||
|
||||
it('should return false on MongoDB connection failure', async () => {
|
||||
// Create a failing client
|
||||
const failingClient = {
|
||||
connect: jest.fn().mockRejectedValue(new Error('Connection failed')),
|
||||
db: jest.fn().mockRejectedValue(new Error('Connection failed')),
|
||||
close: jest.fn()
|
||||
}
|
||||
|
||||
MockedMongoClient.mockImplementation(() => failingClient as any)
|
||||
|
||||
// Clear the module cache and re-import
|
||||
jest.resetModules()
|
||||
const { checkMongoConnection } = await import('./mongodb')
|
||||
|
||||
const result = await checkMongoConnection()
|
||||
expect(result).toBe(false)
|
||||
expect(mockMongoLoggerError).toHaveBeenCalledWith('MongoDB connection check failed', { errorName: 'Error' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('Connection reuse and caching', () => {
|
||||
it('should reuse the same MongoClient instance for multiple calls', async () => {
|
||||
const { getClientPromise } = await import('./mongodb')
|
||||
|
||||
const client1 = await getClientPromise()
|
||||
const client2 = await getClientPromise()
|
||||
|
||||
// Should be the same client instance
|
||||
expect(client1).toBe(client2)
|
||||
})
|
||||
|
||||
it('should not cache a rejected connection promise and retry on next call', async () => {
|
||||
// First attempt fails (e.g. transient DB outage at startup)
|
||||
const failingClient = {
|
||||
connect: jest.fn().mockRejectedValueOnce(new Error('transient failure')),
|
||||
db: jest.fn(),
|
||||
close: jest.fn()
|
||||
}
|
||||
MockedMongoClient.mockImplementation(() => failingClient)
|
||||
|
||||
const { getClientPromise } = await import('./mongodb')
|
||||
|
||||
await expect(getClientPromise()).rejects.toThrow('transient failure')
|
||||
|
||||
// Second call must retry instead of replaying the cached rejection
|
||||
failingClient.connect.mockResolvedValueOnce(failingClient as any)
|
||||
await expect(getClientPromise()).resolves.toBe(failingClient)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,70 +0,0 @@
|
||||
import { MongoClient, Db } from 'mongodb'
|
||||
import { dbLogger, getSafeErrorDetails } from './logger'
|
||||
|
||||
// WHY this file only exposes getDb/checkMongoConnection now: it used to also
|
||||
// export getCollection(), used by src/app/api/contact/route.ts for a raw,
|
||||
// Payload-external `contact_submissions` collection. MITHOME-94 moved that
|
||||
// write to a proper Payload collection (ContactSubmissions) via the Local
|
||||
// API — getDb() itself stays alive only for /api/health's connectivity check.
|
||||
|
||||
const options = {
|
||||
maxPoolSize: 10,
|
||||
serverSelectionTimeoutMS: 5000,
|
||||
socketTimeoutMS: 45000,
|
||||
}
|
||||
|
||||
let clientPromise: Promise<MongoClient> | undefined
|
||||
|
||||
function createClientPromise(): Promise<MongoClient> {
|
||||
const uri = process.env.MONGODB_URI
|
||||
if (!uri) {
|
||||
throw new Error('Please add MONGODB_URI to your environment variables')
|
||||
}
|
||||
|
||||
return new MongoClient(uri, options).connect()
|
||||
}
|
||||
|
||||
export function getClientPromise(): Promise<MongoClient> {
|
||||
// In development mode, use a global variable so that the client is not recreated between hot reloads.
|
||||
// The connection is intentionally created lazily: `next build` must not require runtime secrets.
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
// @ts-expect-error - Global variable for development hot reload
|
||||
if (!global._mongoClientPromise) {
|
||||
// @ts-expect-error - Global variable for development hot reload
|
||||
global._mongoClientPromise = createClientPromise().catch((error: Error) => {
|
||||
// A rejected promise must not stay cached: a transient failure would
|
||||
// otherwise break every subsequent request in this process.
|
||||
// @ts-expect-error - Global variable for development hot reload
|
||||
global._mongoClientPromise = undefined
|
||||
throw error
|
||||
})
|
||||
}
|
||||
// @ts-expect-error - Global variable for development hot reload
|
||||
return global._mongoClientPromise
|
||||
}
|
||||
|
||||
clientPromise ??= createClientPromise().catch((error: Error) => {
|
||||
// See the development branch above: drop the cached rejection so the next
|
||||
// call can retry the connection.
|
||||
clientPromise = undefined
|
||||
throw error
|
||||
})
|
||||
return clientPromise
|
||||
}
|
||||
|
||||
export async function getDb(): Promise<Db> {
|
||||
const client = await getClientPromise()
|
||||
return client.db(process.env.MONGODB_DB || 'mozdit')
|
||||
}
|
||||
|
||||
// Health check for MongoDB connection
|
||||
export async function checkMongoConnection(): Promise<boolean> {
|
||||
try {
|
||||
const db = await getDb()
|
||||
await db.admin().ping()
|
||||
return true
|
||||
} catch (error) {
|
||||
dbLogger.error('MongoDB connection check failed', getSafeErrorDetails(error))
|
||||
return false
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user