Added protecting hooks
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import type { CollectionBeforeDeleteHook } from 'payload'
|
||||
|
||||
import { APIError } from 'payload'
|
||||
|
||||
/**
|
||||
* Blocks deletion of a page assigned a System Page role (homepage,
|
||||
* privacyPolicy, cookiePolicy, termsOfService). An editor deleting the privacy
|
||||
* policy or homepage by accident would break routing and compliance links; this
|
||||
* stops it with a clear error. They must unassign the role first (deliberate).
|
||||
*
|
||||
* Reads the role assignments from SiteSettings (which page holds which role).
|
||||
*
|
||||
* hooks: { beforeDelete: [buildPreventDeleteSystemPage({ settingsSlug: 'site-settings' })] }
|
||||
*/
|
||||
export function buildPreventDeleteSystemPage(
|
||||
args: { roleFields?: string[]; settingsSlug?: string } = {},
|
||||
): CollectionBeforeDeleteHook {
|
||||
const settingsSlug = args.settingsSlug ?? 'site-settings'
|
||||
const roleFields = args.roleFields ?? [
|
||||
'homepage',
|
||||
'privacyPolicy',
|
||||
'cookiePolicy',
|
||||
'termsOfService',
|
||||
]
|
||||
|
||||
return async ({ id, req }) => {
|
||||
const settings = (await req.payload
|
||||
.findGlobal({ slug: settingsSlug as never, depth: 0 })
|
||||
.catch(() => null)) as null | Record<string, unknown>
|
||||
if (!settings) {return}
|
||||
|
||||
for (const field of roleFields) {
|
||||
const assigned = settings[field]
|
||||
const assignedId =
|
||||
assigned && typeof assigned === 'object' ? (assigned as { id?: unknown }).id : assigned
|
||||
if (assignedId != null && String(assignedId) === String(id)) {
|
||||
throw new APIError(
|
||||
`Nie można usunąć strony przypisanej do roli systemowej "${field}". ` +
|
||||
`Najpierw odłącz rolę w Site Settings.`,
|
||||
400,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user