Created
November 22, 2021 14:22
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
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