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:
Radosław Smoliński
2026-11-13 14:29:41 +01:00
co-authored by Claude Opus 5.5
parent 179d5b0d79
commit 748ef9286f
6 changed files with 322 additions and 30 deletions
+11
View File
@@ -8,6 +8,17 @@ versions at once, go through every "Requires project changes" section in order,
version you have. A new release = a new section at the top; we remove the oldest ones only
once there are more than 20.
## Unreleased
### Fixed
- **Seeding a required field with references** (`createSeeder`, `upsertBySlug` / `upsertBy`): a page whose required
`layout` holds a `{ $page }` or `{ $form }` reference can be created. The first pass used to leave the whole field out,
so validation rejected the record ("The following field is invalid: … > Layout") while the dry run reported a create.
Now references to records that exist are resolved in the first pass, so the field is written complete. A link to a
page created later in the same call is filled in the second pass, and a record whose required field needs that page
waits until it exists. Required links in a cycle, and links to a page or form that never appears, are an error with
nothing written. The dry run now reports the same outcome, including a missing form. Seed scripts need no change.
## 1.15.4
### Fixed
@@ -558,7 +558,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| Export | Import from | What it does / when |
|---|---|---|
| `createSeeder(payload, { dryRun?, update?, force?, only?, guard?, editCheck?, context?, pagesCollection?, formsCollection?, label?, log? })` | `@intecion/ipal-kit/seed` | The seed rules in one place → `{ upsertBySlug, upsertBy, fillGlobal, summary, dryRun, update, force, local, only }`. `only` (or `SEED_ONLY`) = the records the run may touch (`pages:kontakt`, `forms:<title>`, `global:<slug>`, `pages:*`), the rest → `skip (not listed)`; a run without it against production / a non-local database throws unless `IPAL_SEED_ALLOW_FULL=1` / `guard.allowFull: true` (after launch: named records only; dry runs are never refused; `guard: false` turns every guard off). Create-only by default, natural keys, never deletes, globals: empty fields only, every locale with `fallbackLocale: false` onto the same row ids, skips records edited since seeding, writes with `context` `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }`. Throws when `update` runs on production / a non-local database without `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Both seed templates use it. |
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). |
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). A required field (layout) with references is written complete in the first write; a link to a page later in the same call waits for it; required cycles and unknown targets are an error with nothing written; the dry run reports the same. |
| `upsertBy(collection, key, data)` | (method) | Matches by other keys, e.g. a form by `{ title }`. |
| `fillGlobal(slug, data)` | (method) | Fills only empty fields of a global — a choice (select, radio, checkbox, number, date) still at its `defaultValue` counts as empty, text never does; a field already holding the seeded value is skipped (all seeded fields with `update` when untouched). |
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, errors }`; exit 1 when `errors`. |
+14 -2
View File
@@ -203,12 +203,24 @@ language the same rows in the same order (its texts differ; non-localized values
from the last language written). A field with `localized: true` keeps its own rows per language.
`{ $page: 'kontakt' }` becomes the ID of the page whose default-locale slug is `kontakt`;
`{ $form: 'Contact form' }` becomes the ID of the form with that title (seed the form first). A missing form
is an error for that record, never an empty relation. Ready pages made of library blocks:
is an error for that record, never an empty relation.
**References and required fields.** A new record is created complete, so a required field (a `layout` whose block
links to a page or form) passes validation:
- a reference to a record that exists — or was created earlier in the run — becomes its ID in the first write;
- a `{ $page }` to a page created later **in the same `upsertBySlug` call** is filled in the second pass; when the
field that holds it is required, the record waits until that page exists. Pages that link to each other belong in
one call (an array);
- required links in a cycle (A needs B, B needs A) and a reference to a page or form that does not exist and is not
planned are an **error** for those records, and nothing is written for them. Make one of the links optional, or seed
one of the pages first;
- the dry run reports the same outcome. A form planned earlier in the same dry run counts as existing. Only a required
cycle shows up first in the real run, because the dry run does not validate fields. Ready pages made of library blocks:
`pageTemplates` in [block-library.md](./block-library.md#page-templates).
| Method | What it does |
|---|---|
| `upsertBySlug(collection, data \| data[], { slugField })` | matches by the default-locale slug (`slugField`, default `slug`). With an array, missing records are created first (without fields that hold `$page` / `$form` links), then every record gets its full content, so pages can link to each other in any order |
| `upsertBySlug(collection, data \| data[], { slugField })` | matches by the default-locale slug (`slugField`, default `slug`). With an array, missing records are created first (references to existing records resolved, links to pages later in the call filled in pass 2; a required one waits for its page), then every record gets its full content, so pages can link to each other in any order. Unknown targets and required cycles: error, nothing written |
| `upsertBy(collection, key, data)` | matches by other natural keys, e.g. `{ title: 'Contact form' }` (all keys must match, default locale) |
| `fillGlobal(slug, data)` | fills only the global's empty fields (the default locale decides). A choice — select, radio, checkbox, number, date — still at the field's `defaultValue` counts as empty (Payload stores defaults on the first save, so `defaultTheme: 'system'` can be seeded over `light`); text is never treated so, even when it equals a default. A field that already holds exactly the seeded value is not written (`skip (exists)`), so re-running a seed of defaults changes nothing. With `update` and an untouched global: every seeded field |
| `summary()` | prints the summary and returns `{ created, skipped, updated, skippedEdited, errors }` |
@@ -558,7 +558,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| Export | Import from | What it does / when |
|---|---|---|
| `createSeeder(payload, { dryRun?, update?, force?, only?, guard?, editCheck?, context?, pagesCollection?, formsCollection?, label?, log? })` | `@intecion/ipal-kit/seed` | The seed rules in one place → `{ upsertBySlug, upsertBy, fillGlobal, summary, dryRun, update, force, local, only }`. `only` (or `SEED_ONLY`) = the records the run may touch (`pages:kontakt`, `forms:<title>`, `global:<slug>`, `pages:*`), the rest → `skip (not listed)`; a run without it against production / a non-local database throws unless `IPAL_SEED_ALLOW_FULL=1` / `guard.allowFull: true` (after launch: named records only; dry runs are never refused; `guard: false` turns every guard off). Create-only by default, natural keys, never deletes, globals: empty fields only, every locale with `fallbackLocale: false` onto the same row ids, skips records edited since seeding, writes with `context` `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }`. Throws when `update` runs on production / a non-local database without `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Both seed templates use it. |
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). |
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). A required field (layout) with references is written complete in the first write; a link to a page later in the same call waits for it; required cycles and unknown targets are an error with nothing written; the dry run reports the same. |
| `upsertBy(collection, key, data)` | (method) | Matches by other keys, e.g. a form by `{ title }`. |
| `fillGlobal(slug, data)` | (method) | Fills only empty fields of a global — a choice (select, radio, checkbox, number, date) still at its `defaultValue` counts as empty, text never does; a field already holding the seeded value is skipped (all seeded fields with `update` when untouched). |
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, errors }`; exit 1 when `errors`. |
+107 -26
View File
@@ -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).
+188
View File
@@ -0,0 +1,188 @@
import type { Block, Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'node:os'
import path from 'node:path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import type { SeedResult } from '../src/exports/seed.js'
import { createSeeder } from '../src/exports/seed.js'
import { buildLinksField, buildSectionHeaderField } from '../src/index.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
/**
* Regression (vanstevpl-web, 1.15.4): a page whose REQUIRED layout holds a { $page } / { $form } reference
* could not be created — pass 1 left the whole field out and validation rejected the record, while the dry
* run reported a create. Now pass 1 resolves references to existing records, retries records whose required
* fields wait for pages created later in the same call, and reports cycles and unknown targets as errors
* with nothing written. The dry run reports the same outcome.
*/
const LOCALES = ['pl', 'en', 'de'] as const
const callToAction: Block = { slug: 'callToAction', fields: [buildSectionHeaderField(), buildLinksField()] }
const formBlock: Block = { slug: 'formBlock', fields: [{ name: 'form', type: 'relationship', relationTo: 'forms', required: true }] }
// A block whose link to another page is required — forward references to it must wait.
const teaser: Block = { slug: 'teaser', fields: [{ name: 'target', type: 'relationship', relationTo: 'pages', required: true }] }
const confirmation = {
root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: 'Thanks', version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 },
}
/** A page with a required layout of one block. */
const page = (slug: string, title: string, layout: Record<string, unknown>[]) => ({
slug: { de: `${slug}-de`, en: `${slug}-en`, pl: slug },
layout,
title: { de: `${title} DE`, en: `${title} EN`, pl: title },
})
const teaserTo = (slug: string) => ({ blockType: 'teaser', target: { $page: slug } })
describe('createSeeder: required fields with references', () => {
let payload: Payload
beforeAll(async () => {
vi.stubEnv('DATABASE_URI', 'file::memory:')
const config = buildTestConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{
slug: 'pages',
fields: [
{ name: 'title', type: 'text', localized: true, required: true },
{ name: 'slug', type: 'text', index: true, localized: true },
{ name: 'layout', type: 'blocks', blocks: [callToAction, formBlock, teaser], required: true },
],
},
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-seed-refs') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
localization: { defaultLocale: 'pl', fallback: true, locales: [...LOCALES] },
plugins: [
ipalKit({
forms: {},
i18n: { defaultLocale: 'pl', locales: LOCALES.map((code) => ({ code, label: code.toUpperCase() })) },
pages: { slug: 'pages' },
twoFactor: false,
} as never),
],
secret: 'seed-required-refs',
telemetry: false,
})
payload = await getPayload({ config })
// The existing records the references point at.
const seed = createSeeder(payload, { log: () => {} })
await seed.upsertBySlug('pages', page('kontakt', 'Kontakt', [{ blockType: 'callToAction', header: { heading: { de: 'Hallo', en: 'Hello', pl: 'Cześć' } } }]))
await seed.upsertBy('forms', { title: 'Contact form' }, { confirmationMessage: confirmation, confirmationType: 'message', fields: [{ name: 'name', blockType: 'text', label: 'Name' }], title: 'Contact form' })
}, 60_000)
afterAll(async () => {
vi.unstubAllEnvs()
await payload?.destroy()
})
const seeder = (dryRun = false) => createSeeder(payload, { dryRun, log: () => {}, update: false })
const idOf = async (slug: string) => (await payload.find({ collection: 'pages', depth: 0, locale: 'pl', where: { slug: { equals: slug } } })).docs[0]?.id
const count = async () => (await payload.count({ collection: 'pages' })).totalDocs
/** Runs the same seed as a dry run, then for real: both must report the same statuses. */
const both = async (run: (seed: ReturnType<typeof seeder>) => Promise<SeedResult | SeedResult[]>) => {
const planned = [await run(seeder(true))].flat().map((r) => r.status)
const done = [await run(seeder())].flat()
expect(done.map((r) => r.status)).toEqual(planned)
return done
}
test('the report’s careers page: a required layout linking to an existing page, in pl, en and de', async () => {
const careers = {
slug: { de: 'karriere', en: 'careers', pl: 'kariera' },
layout: [
{
blockType: 'callToAction',
header: { heading: { de: 'Kontakt', en: 'Contact', pl: 'Kontakt' } },
links: [{ link: { type: 'internal', page: { $page: 'kontakt' } } }],
},
],
title: { de: 'Karriere', en: 'Careers', pl: 'Kariera' },
}
const [result] = await both(async (seed) => [await seed.upsertBySlug('pages', careers)])
expect(result).toMatchObject({ status: 'create' })
const all = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 0, fallbackLocale: false as never, locale: 'all' as never })) as unknown as {
layout: { header: { heading: Record<string, string> }; id: string; links: { link: { page: unknown } }[] }[]
}
expect(all.layout).toHaveLength(1)
expect(all.layout[0].header.heading).toEqual({ de: 'Kontakt', en: 'Contact', pl: 'Kontakt' })
expect(all.layout[0].links[0].link.page).toBe(await idOf('kontakt'))
// One set of rows in every locale (1.15.4).
for (const locale of LOCALES) {
const doc = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 0, fallbackLocale: false, locale })) as unknown as { layout: { id: string }[] }
expect(doc.layout[0].id).toBe(all.layout[0].id)
}
// Create-only: a second run changes nothing.
expect(await seeder().upsertBySlug('pages', careers)).toMatchObject({ status: 'skip (exists)' })
})
test('a required layout with a form block pointing at an existing form', async () => {
const [result] = await both(async (seed) => [await seed.upsertBySlug('pages', page('formularz', 'Formularz', [{ blockType: 'formBlock', form: { $form: 'Contact form' } }]))])
expect(result).toMatchObject({ status: 'create' })
const doc = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 1, locale: 'pl' })) as unknown as { layout: { form: { title: string } }[] }
expect(doc.layout[0].form.title).toBe('Contact form')
})
test('forward references in one call: an optional link is filled in pass 2, a required one waits for its page', async () => {
const results = await both((seed) =>
seed.upsertBySlug('pages', [
// Optional link (CTA) to a page later in the list.
page('o-nas', 'O nas', [{ blockType: 'callToAction', links: [{ link: { type: 'internal', page: { $page: 'oferta' } } }] }]),
// Required link to a page later in the list: created once that page exists.
page('start', 'Start', [teaserTo('oferta')]),
page('oferta', 'Oferta', [{ blockType: 'callToAction', header: { heading: { de: 'Angebot', en: 'Offer', pl: 'Oferta' } } }]),
]),
)
expect(results.map((r) => r.status)).toEqual(['create', 'create', 'create'])
const oferta = await idOf('oferta')
const about = (await payload.findByID({ id: (await idOf('o-nas')), collection: 'pages', depth: 0, locale: 'en' })) as unknown as { layout: { links: { link: { page: unknown } }[] }[] }
expect(about.layout[0].links[0].link.page).toBe(oferta)
const start = (await payload.findByID({ id: (await idOf('start')), collection: 'pages', depth: 0, locale: 'de' })) as unknown as { layout: { target: unknown }[] }
expect(start.layout[0].target).toBe(oferta)
// Second run: everything exists, nothing written.
const again = await seeder().upsertBySlug('pages', [page('o-nas', 'O nas', []), page('start', 'Start', []), page('oferta', 'Oferta', [])])
expect(again.map((r) => r.status)).toEqual(['skip (exists)', 'skip (exists)', 'skip (exists)'])
})
test('required references in a cycle: a clear error, nothing written', async () => {
const before = await count()
const results = await seeder().upsertBySlug('pages', [page('jeden', 'Jeden', [teaserTo('dwa')]), page('dwa', 'Dwa', [teaserTo('jeden')])])
expect(results.map((r) => r.status)).toEqual(['error', 'error'])
expect(results[0].note).toMatch(/required references to pages not created yet \("dwa"\) — a cycle of required links/)
expect(await count()).toBe(before)
})
test('a reference to a page that never appears: an error in the dry run and the real run, nothing written', async () => {
const before = await count()
const results = await both(async (seed) => [await seed.upsertBySlug('pages', page('sierota', 'Sierota', [teaserTo('nie-ma-takiej')]))])
expect(results[0]).toMatchObject({ status: 'error' })
expect(results[0].note).toMatch(/\$page "nie-ma-takiej" not found/)
expect(await count()).toBe(before)
})
test('a reference to a form that does not exist: an error in the dry run too', async () => {
const results = await both(async (seed) => [await seed.upsertBySlug('pages', page('bez-formularza', 'Bez', [{ blockType: 'formBlock', form: { $form: 'Missing form' } }]))])
expect(results[0]).toMatchObject({ status: 'error' })
expect(results[0].note).toMatch(/\$form "Missing form" not found/)
})
test('dry run: a form planned earlier in the same run counts as there', async () => {
const seed = seeder(true)
expect(await seed.upsertBy('forms', { title: 'Newsletter' }, { confirmationMessage: confirmation, confirmationType: 'message', fields: [], title: 'Newsletter' })).toMatchObject({ status: 'create' })
expect(await seed.upsertBySlug('pages', page('newsletter', 'Newsletter', [{ blockType: 'formBlock', form: { $form: 'Newsletter' } }]))).toMatchObject({ status: 'create' })
})
})