Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions packages/plugin-nested-docs/src/utilities/getParents.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { CollectionConfig, Document, PayloadRequest } from 'payload'

import { APIError } from 'payload'

import type { NestedDocsPluginConfig } from '../types.js'

export const getParents = async (
Expand All @@ -14,6 +16,15 @@ export const getParents = async (
let retrievedParent: null | Record<string, unknown> = null

if (parent) {
const parentID = typeof parent === 'object' ? (parent as Record<string, unknown>).id : parent

// Detect circular parent references to prevent infinite recursion
if (docs.some((d) => d.id === parentID)) {
throw new APIError(
'Circular parent reference detected. A document cannot be its own ancestor.',
)
}

// If not auto-populated, and we have an ID
if (typeof parent === 'string' || typeof parent === 'number') {
retrievedParent = await req.payload.findByID({
Expand Down
78 changes: 78 additions & 0 deletions test/plugin-nested-docs/int.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,84 @@ describe('@payloadcms/plugin-nested-docs', () => {
})
})

describe('circular references', () => {
const createdPageIDs: (number | string)[] = []

afterEach(async () => {
for (const id of [...createdPageIDs].reverse()) {
await payload.delete({ collection: 'pages', id })
}
createdPageIDs.length = 0
})

it('should throw an error when setting a page as its own parent', async () => {
const page = await payload.create({
collection: 'pages',
data: {
title: 'Self Parent',
slug: 'self-parent',
},
})

createdPageIDs.push(page.id)

await expect(
payload.update({
collection: 'pages',
id: page.id,
data: {
parent: page.id,
},
}),
).rejects.toThrow(/[Cc]ircular/)
})

it('should throw an error when creating a circular parent chain', async () => {
const pageA = await payload.create({
collection: 'pages',
data: {
title: 'Circle A',
slug: 'circle-a',
},
})

createdPageIDs.push(pageA.id)

const pageB = await payload.create({
collection: 'pages',
data: {
title: 'Circle B',
slug: 'circle-b',
parent: pageA.id,
},
})

createdPageIDs.push(pageB.id)

const pageC = await payload.create({
collection: 'pages',
data: {
title: 'Circle C',
slug: 'circle-c',
parent: pageB.id,
},
})

createdPageIDs.push(pageC.id)

// Setting A's parent to C creates a cycle: A -> C -> B -> A
await expect(
payload.update({
collection: 'pages',
id: pageA.id,
data: {
parent: pageC.id,
},
}),
).rejects.toThrow(/[Cc]ircular/)
})
})

describe('versions', () => {
const createdPageIDs: (number | string)[] = []

Expand Down
Loading