Skip to content

Instantly share code, notes, and snippets.

@fabien

fabien/colour.js Secret

Last active May 18, 2024 13:05
Show Gist options
  • Save fabien/409e1151574266faf68fcb15a9b6b948 to your computer and use it in GitHub Desktop.
Save fabien/409e1151574266faf68fcb15a9b6b948 to your computer and use it in GitHub Desktop.
import client from 'part:@sanity/base/client';
import groq from 'groq';
const isUniqueColour = (colour, context) => {
const { document } = context;
const id = document._id.replace(/^drafts\./, '');
const params = {
draft: `drafts.${id}`,
published: id,
colour,
};
/* groq */
const query = groq`!defined(*[
_type == 'colour' &&
!(_id in [$draft, $published]) &&
name == $colour
][0]._id)`;
return client.fetch(query, params);
};
export default {
title: 'Colour',
name: 'colour',
type: 'document',
fields: [
{
title: 'Name',
name: 'name',
type: 'string',
validation: (Rule) =>
Rule.custom(async (value, context) => {
const isUnique = await isUniqueColour(value, context);
if (!isUnique) return 'Colour is not unique';
return true;
}),
},
],
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment