Skip to content

Instantly share code, notes, and snippets.

@SimeonGriggs
Created November 22, 2021 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SimeonGriggs/cdb207243054d7a6259e48a79eca7a54 to your computer and use it in GitHub Desktop.
Save SimeonGriggs/cdb207243054d7a6259e48a79eca7a54 to your computer and use it in GitHub Desktop.
An `isUnique` function for unique slugs across a schema type but the same across a base document
{
name: 'slug',
title: 'Slug',
type: 'slug',
options: {
source: 'title',
isUnique: async (slug, options) => {
const {document: sanityDocument} = options
// Filter out additional parts of the _id to get the original
const baseId = sanityDocument._id
.split(`.`) // Replace with your delimeter if not using subpath
.filter((idPart) => ![`drafts`, `i18n`, sanityDocument.__i18n_lang].includes(idPart))
.join(`.`)
const type = sanityDocument._type
// 1. Check all documents of this same _type
// 2. With this same slug
// 3. But not with this same base _id
const query = `*[_type == $type && slug.current == $slug && !(_id match $baseId)]`
const params = {slug, type, baseId}
const matchingSlugs = await client.fetch(query, params)
return !matchingSlugs.length
},
},
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment