Skip to content

Commit

Permalink
Merge pull request #16 from Q42/fix/slug-validator-error-message
Browse files Browse the repository at this point in the history
Fix: slug validator error message
  • Loading branch information
djohalo2 authored Jan 22, 2024
2 parents bb63c7d + 7531b2f commit 117e371
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions src/validators/slug-validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,22 @@ export const slugValidator =
const allPages = await client.fetch<RawPageMetadata[]>(getRawPageMetadataQuery(config));
const siblingPages = allPages.filter(page => page.parent?._ref === parentRef._ref);

const hasDuplicateSlugWithinParent = siblingPages
.filter(child => child._id.replace(DRAFTS_PREFIX, '') !== context.document?._id.replace(DRAFTS_PREFIX, ''))
.some(child => child.slug?.current === slug?.current);
const siblingPagesWithSameSlug = siblingPages
.filter(page => page._id.replace(DRAFTS_PREFIX, '') !== context.document?._id.replace(DRAFTS_PREFIX, ''))
.filter(page => page.slug?.current === slug?.current);

if (hasDuplicateSlugWithinParent) {
return 'Slug must be unique.';
if (siblingPagesWithSameSlug.length) {
// If there is a sibling page with the same slug published, but a different slug in a draft, we want to show a more specific validation error to the user instead.
const siblingDraftPageWithSameSlug = siblingPages.find(
page =>
page._id.startsWith(DRAFTS_PREFIX) &&
page._id.includes(siblingPagesWithSameSlug[0]._id) &&
page.slug?.current !== slug?.current,
);

return siblingDraftPageWithSameSlug
? `Slug must be unique. Another page with the same slug is already published, but has a draft version with a different slug: "${siblingDraftPageWithSameSlug.slug?.current}". Publish that page first or change the slug to something else.`
: 'Slug must be unique.';
}

return true;
Expand Down

0 comments on commit 117e371

Please sign in to comment.