Seeder: required fields with references are created complete (1.15.5)
A page whose required layout holds a { $page } / { $form } reference could not be
created: pass 1 left the whole field out, validation rejected the record, and the
dry run reported a create (vanstevpl-web, 1.15.4).
- pass 1 resolves references to records that exist (or were created earlier in
the run), so the field is written complete
- a { $page } to a page later in the same call is null in pass 1 and filled in
pass 2; a record whose required field needs it is retried once that page exists
- required links in a cycle and references to pages or forms that never appear
are an error with nothing written; unknown page targets are found while
planning, so the dry run reports them too
- dry run: a missing form is an error (was a placeholder); a form planned earlier
in the same dry run counts as existing
- real-Payload tests (pl, en, de): the report's careers page, an existing form
target, optional and required forward links, a cycle, missing page and form,
create-only second runs, dry-run parity
- CHANGELOG Unreleased, seeding.md, api.md; reference skills refreshed
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
179d5b0d79
commit
748ef9286f
+107
-26
@@ -172,11 +172,22 @@ const formRef = (v: object): string | undefined => {
|
||||
return typeof ref === 'string' ? ref : undefined
|
||||
}
|
||||
|
||||
/** True when the value holds a { $page } or { $form } reference — such fields are written once refs resolve. */
|
||||
const hasRef = (v: unknown): boolean =>
|
||||
Array.isArray(v)
|
||||
? v.some(hasRef)
|
||||
: !!v && typeof v === 'object' && (typeof (v as { $page?: unknown }).$page === 'string' || formRef(v) !== undefined || Object.values(v).some(hasRef))
|
||||
const pageRef = (v: object): string | undefined => {
|
||||
const ref = (v as { $page?: unknown }).$page
|
||||
return typeof ref === 'string' ? ref : undefined
|
||||
}
|
||||
|
||||
/** The default-locale slugs of the { $page } references a value holds. */
|
||||
const pageRefsIn = (v: unknown, out = new Set<string>()): Set<string> => {
|
||||
if (Array.isArray(v)) {v.forEach((x) => pageRefsIn(x, out))}
|
||||
else if (v && typeof v === 'object') {
|
||||
const ref = pageRef(v)
|
||||
if (ref !== undefined) {out.add(ref)}
|
||||
else {Object.values(v).forEach((x) => pageRefsIn(x, out))}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
|
||||
export function createSeeder(payload: BasePayload, options: SeederOptions = {}): Seeder {
|
||||
// Payload is up (the caller passed it in) — the run's exit guard, if any, now waits for summary()
|
||||
@@ -229,6 +240,8 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
const localeKeys = codes.length ? codes : [undefined]
|
||||
const counts: Record<SeedStatus, number> = { create: 0, error: 0, 'skip (edited)': 0, 'skip (exists)': 0, 'skip (not listed)': 0, update: 0 }
|
||||
const pageIds = new Map<string, number | string>()
|
||||
/** Forms planned for creation in a dry run, by title — a later { $form } to them is not an error. */
|
||||
const plannedForms = new Set<string>()
|
||||
|
||||
log(
|
||||
`${label} ${dryRun ? 'DRY RUN — nothing is written' : 'writing'} · ${update ? `updates on${force ? ' (FORCE: edited records too)' : ''}` : 'create-only'} · database ${local ? 'local' : 'NOT local'} · ${only ? `only: ${only.join(', ')}` : 'all records'}\n`,
|
||||
@@ -278,11 +291,12 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
if (form !== undefined) {
|
||||
const id = await findId(formsCollection, { title: form })
|
||||
if (id !== undefined) {return id}
|
||||
if (lenient || dryRun) {return `(form:${form})`}
|
||||
// A dry run reports what the real run would do: a form planned earlier in this run will exist.
|
||||
if (lenient || (dryRun && plannedForms.has(form))) {return `(form:${form})`}
|
||||
throw new Error(`$form "${form}" not found — seed that form first or create it in the panel`)
|
||||
}
|
||||
const ref = (v as { $page?: unknown }).$page
|
||||
if (typeof ref === 'string') {
|
||||
const ref = pageRef(v)
|
||||
if (ref !== undefined) {
|
||||
let id = pageIds.get(ref)
|
||||
if (id === undefined) {
|
||||
id = await findId(pagesCollection, { slug: ref })
|
||||
@@ -299,6 +313,34 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* The first-pass value of a record being created: references to records that exist now become their ids,
|
||||
* so a required field (a layout whose block links to a page) is written complete. A { $page } to a page
|
||||
* planned in the same call and not created yet (`forward`) becomes null and is collected; pass 2 writes it.
|
||||
* Any other unknown target throws — nothing is written for that record.
|
||||
*/
|
||||
const resolveForCreate = async (v: unknown, forward: Set<string>, planned: Set<string>): Promise<unknown> => {
|
||||
if (Array.isArray(v)) {return Promise.all(v.map((x) => resolveForCreate(x, forward, planned)))}
|
||||
if (!v || typeof v !== 'object') {return v}
|
||||
if (formRef(v) !== undefined) {return resolveRefs(v)}
|
||||
const ref = pageRef(v)
|
||||
if (ref !== undefined) {
|
||||
const known = pageIds.get(ref) ?? (await findId(pagesCollection, { slug: ref }))
|
||||
if (known !== undefined) {
|
||||
pageIds.set(ref, known)
|
||||
return known
|
||||
}
|
||||
if (planned.has(ref)) {
|
||||
forward.add(ref)
|
||||
return null
|
||||
}
|
||||
throw new Error(`$page "${ref}" not found — seed that page first or create it in the panel`)
|
||||
}
|
||||
const out: Record<string, unknown> = {}
|
||||
for (const [k, x] of Object.entries(v)) {out[k] = await resolveForCreate(x, forward, planned)}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Per-locale seed values (refs resolved) — what the hash describes. */
|
||||
const perLocale = (data: unknown) => Object.fromEntries(localeKeys.map((l) => [l ?? '-', localize(data, l, undefined, codes)]))
|
||||
|
||||
@@ -325,6 +367,7 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
|
||||
// Plan: one status per record, decided before anything is written.
|
||||
const plan: Planned[] = []
|
||||
const plannedHere = new Set(trackPages ? items.map((i) => i.key.slug).filter((s): s is string => typeof s === 'string') : [])
|
||||
for (const item of items) {
|
||||
const p: Planned = { ...item }
|
||||
plan.push(p)
|
||||
@@ -332,8 +375,14 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
p.id = await findId(collection, item.key)
|
||||
const slug = typeof item.key.slug === 'string' ? item.key.slug : undefined
|
||||
if (p.id === undefined) {
|
||||
// Every { $page } must exist already or be planned in this call — otherwise nothing is written (dry run too).
|
||||
for (const ref of pageRefsIn(item.data)) {
|
||||
if (plannedHere.has(ref) || pageIds.has(ref) || (await findId(pagesCollection, { slug: ref })) !== undefined) {continue}
|
||||
throw new Error(`$page "${ref}" not found — seed that page first or create it in the panel`)
|
||||
}
|
||||
p.action = 'create'
|
||||
if (dryRun && trackPages && slug) {pageIds.set(slug, `(new:${slug})`)}
|
||||
if (dryRun && collection === formsCollection && typeof item.key.title === 'string') {plannedForms.add(item.key.title)}
|
||||
continue
|
||||
}
|
||||
if (trackPages && slug) {pageIds.set(slug, p.id)}
|
||||
@@ -352,27 +401,59 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 1: create missing records without fields that reference other pages (they may not exist yet).
|
||||
// Pass 1: create missing records complete — references to existing records resolved. A forward { $page }
|
||||
// (a page created later in this call) is null for now; a record whose required field needs it is retried
|
||||
// once that page exists. Required references in a cycle, or to a page that never appears, are an error
|
||||
// and nothing is written for those records.
|
||||
if (!dryRun) {
|
||||
for (const p of plan) {
|
||||
if (p.action !== 'create') {continue}
|
||||
try {
|
||||
const first = Object.fromEntries(Object.entries(p.data).filter(([, v]) => !hasRef(v)))
|
||||
const created = await payload.create({
|
||||
collection: collection as never,
|
||||
context,
|
||||
data: localize(first, defaultLocale, undefined, codes) as never,
|
||||
depth: 0,
|
||||
...(defaultLocale ? { locale: defaultLocale as never } : {}),
|
||||
})
|
||||
p.id = (created as { id: number | string }).id
|
||||
const slug = p.key.slug
|
||||
if (trackPages && typeof slug === 'string') {pageIds.set(slug, p.id)}
|
||||
} catch (e) {
|
||||
p.result = { label: p.label, note: (e as Error).message, status: 'error' }
|
||||
p.action = undefined
|
||||
const waiting = plan.filter((p) => p.action === 'create' && !p.result)
|
||||
const planned = new Set(trackPages ? waiting.map((p) => p.key.slug).filter((s): s is string => typeof s === 'string') : [])
|
||||
const blocked = new Map<Planned, { error: string; forward: Set<string> }>()
|
||||
let progress = true
|
||||
while (waiting.length && progress) {
|
||||
progress = false
|
||||
for (const p of [...waiting]) {
|
||||
const forward = new Set<string>()
|
||||
try {
|
||||
const first = (await resolveForCreate(p.data, forward, planned)) as Record<string, unknown>
|
||||
const created = await payload.create({
|
||||
collection: collection as never,
|
||||
context,
|
||||
data: localize(first, defaultLocale, undefined, codes) as never,
|
||||
depth: 0,
|
||||
...(defaultLocale ? { locale: defaultLocale as never } : {}),
|
||||
})
|
||||
p.id = (created as { id: number | string }).id
|
||||
const slug = p.key.slug
|
||||
if (trackPages && typeof slug === 'string') {
|
||||
pageIds.set(slug, p.id)
|
||||
planned.delete(slug)
|
||||
}
|
||||
waiting.splice(waiting.indexOf(p), 1)
|
||||
blocked.delete(p)
|
||||
progress = true
|
||||
} catch (e) {
|
||||
if (forward.size) {
|
||||
// Valid only once the pages it links to exist — try again after the others.
|
||||
blocked.set(p, { error: (e as Error).message, forward })
|
||||
continue
|
||||
}
|
||||
p.result = { label: p.label, note: (e as Error).message, status: 'error' }
|
||||
p.action = undefined
|
||||
waiting.splice(waiting.indexOf(p), 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const p of waiting) {
|
||||
const why = blocked.get(p)
|
||||
const targets = [...(why?.forward ?? [])].map((s) => `"${s}"`).join(', ')
|
||||
p.result = {
|
||||
label: p.label,
|
||||
note: `required references to pages not created yet (${targets}) — a cycle of required links; make one link optional or seed that page first${why ? ` (${why.error})` : ''}`,
|
||||
status: 'error',
|
||||
}
|
||||
p.action = undefined
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 2: full content in every locale (dry run: resolve refs to report broken ones).
|
||||
|
||||
Reference in New Issue
Block a user