Skip to content

Commit

Permalink
feat(customerCase): check if slug is unique across customer cases, no…
Browse files Browse the repository at this point in the history
…t all documents (#750)
  • Loading branch information
mathiazom authored Oct 10, 2024
1 parent cdc3fe3 commit 973c8cc
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
21 changes: 12 additions & 9 deletions studio/schemas/schemaTypes/slug.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { groq } from "next-sanity";
import {
SlugValidationContext,
SlugValue,
Expand All @@ -13,26 +14,28 @@ import {
isPublished,
} from "studio/utils/documentUtils";

function isSlugUniqueAcrossAllDocuments(
export function isSlugUniqueAcrossDocuments(
slug: string,
{ document, getClient }: SlugValidationContext,
documentType?: string,
) {
if (document === undefined) {
return true;
}
const language = "language" in document ? document.language : undefined;
const isUniqueQuery =
language !== undefined
? `
!defined(*[!(_id in [$draft, $published]) && slug.current == $slug && language == $language][0]._id)
`
: `
!defined(*[!(_id in [$draft, $published]) && slug.current == $slug][0]._id)
const isUniqueQuery = groq`
count(*[
!(_id in [$draft, $published])
&& slug.current == $slug
${documentType !== undefined ? `&& _type == $documentType` : ""}
${language !== undefined ? " && language == $language" : ""}
]) == 0
`;
return getClient({ apiVersion }).fetch<boolean>(isUniqueQuery, {
draft: buildDraftId(document._id),
published: buildPublishedId(document._id),
slug,
...(documentType !== undefined ? { documentType } : {}),
...(language !== undefined ? { language } : {}),
});
}
Expand Down Expand Up @@ -92,7 +95,7 @@ function createSlugField(source: string) {
source,
maxLength: SLUG_MAX_LENGTH,
slugify,
isUnique: isSlugUniqueAcrossAllDocuments,
isUnique: isSlugUniqueAcrossDocuments,
},
validation: (rule) =>
rule
Expand Down
14 changes: 12 additions & 2 deletions studioShared/schemas/documents/customerCase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import { defineField, defineType } from "sanity";

import languageSchemaField from "i18n/languageSchemaField";
import { richText, title } from "studio/schemas/fields/text";
import { titleSlug } from "studio/schemas/schemaTypes/slug";
import {
isSlugUniqueAcrossDocuments,
titleSlug,
} from "studio/schemas/schemaTypes/slug";

export const customerCaseID = "customerCase";

Expand All @@ -13,7 +16,14 @@ const customerCase = defineType({
fields: [
languageSchemaField,
title,
titleSlug,
{
...titleSlug,
options: {
...titleSlug.options,
isUnique: (slug, ctx) =>
isSlugUniqueAcrossDocuments(slug, ctx, customerCaseID),
},
},
defineField({
...richText,
description: "Enter the body content of the Customer case.",
Expand Down

0 comments on commit 973c8cc

Please sign in to comment.