Bouw een geavanceerde Sanity CMS contentvalidatie en automatisering
description
Met deze prompt kan ik mijn Sanity CMS configureren om automatisch inhoud te valideren en contentprocessen te automatiseren, wat fouten vermindert en de efficiëntie verhoogt. Dit is beter dan handmatige controles omdat het consistentie garandeert en tijd bespaart.
prompt
Help me een geavanceerd contentvalidatie- en automatiseringsscript te ontwerpen voor mijn Sanity CMS projec ...
try_prompt
generate_helper
disclaimerOnPageApi
tags
ai_answers
provider: openai
model: gpt-4.1-nano
Natuurlijk! Hier is een voorbeeld van een geavanceerd contentvalidatie- en automatiseringsscript voor je Sanity CMS project, inclusief de door jou gevraagde regels:
1. Verplichte titel
2. Unieke URL (slug)
3. Notificatie bij publicatie
---
**1. Validatie:**
Gebruik de Sanity schema-definitie met validatieregels:
```js
export default {
name: 'article',
title: 'Artikel',
type: 'document',
fields: [
{
name: 'title',
title: 'Titel',
type: 'string',
validation: Rule => Rule.required().error('De titel is verplicht'),
},
{
name: 'slug',
title: 'URL Slug',
type: 'slug',
options: {
source: 'title',
maxLength: 96,
},
validation: Rule => Rule.required().custom(async (slug, context) => {
if (!slug) return true; // vereist al door Rule.required()
const { getClient } = require('part:@sanity/base/client');
const client = getClient({ apiVersion: '2023-10-01' });
const count = await client.fetch(
`count(*[slug.current == $slug])`,
{ slug: slug.current }
);
if (count > 0) {
return 'Deze URL is al in gebruik';
}
return true;
}),
},
// andere velden...
],
preview: {
select: {
title: 'title',
},
},
};
```
**2. Automatisering / notificatie bij publicatie:**
Gebruik Sanity's `publish` hook via een webhook of een `document` event. Bijvoorbeeld met een webhook:
- Maak een webhook in Sanity die getriggerd wordt bij publicatie.
- Laat deze webhook een server-side script aanroepen dat een notificatie verstuurt (bijvoorbeeld via Slack, e-mail, etc.).
**Voorbeeld van een webhook-implementatie (bijvoorbeeld in Node.js):**
```js
// webhook.js
const fetch = require('node-fetch');
async function handleWebhook(req, res) {
const payload = req.body;
if (payload._action === 'publish') {
const title = payload.document?.displayed?.title || 'Een artikel';
await fetch('https://your-notificatie-endpoint', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: `Artikel "${title}" is gepubliceerd.` }),
});
}
res.status(200).end();
}
```
---
**Samenvatting:**
- Voeg de validatieregels toe in je schema (verplichte titel en unieke slug).
- Implementeer een webhook die getriggerd wordt bij publicatie voor notificaties.
Wil je dat ik een compleet voorbeeld van de webhook-instelling of meer geavanceerde automatisering?
provider: deepseek
model: deepseek-chat
Hier is een geavanceerd validatie- en automatiseringsscript voor Sanity CMS:
```javascript
// schemaTypes/yourDocumentType.js
export default {
name: 'yourDocumentType',
title: 'Jouw Documenttype',
type: 'document',
fields: [
{
name: 'title',
title: 'Titel*',
type: 'string',
validation: (Rule) => Rule.required().error('Titel is verplicht'),
},
{
name: 'slug',
title: 'URL Slug',
type: 'slug',
options: {
source: 'title',
maxLength: 96,
isUnique: async (slug, context) => {
const {document, getClient} = context
const client = getClient({apiVersion: '2023-05-03'})
const id = document._id.replace(/^drafts\./, '')
const query = `*[_type == "yourDocumentType" && slug.current == $slug && _id != $id]`
const params = {slug: slug, id: id}
const result = await client.fetch(query, params)
return result.length === 0
}
},
validation: (Rule) => Rule.custom(async (slug, context) => {
if (!slug) return 'URL is verplicht'
const isUnique = await context.getClient({apiVersion: '2023-05-03'})
.fetch(`count(*[_type == "yourDocumentType" && slug.current == $slug && _id != $id])`, {
slug: slug.current,
id: context.document._id.replace(/^drafts\./, '')
})
return isUnique === 0 ? true : 'Deze URL bestaat al. Kies een unieke URL.'
})
},
// overige velden...
],
// Automatisering: Notificatie bij publicatie
__experimental_actions: ['create', 'update', 'delete', 'publish'],
// Document actions voor notificaties
actions: (props) => {
const originalActions = props.actions || []
return originalActions.map(action => {
if (action.action === 'publish') {
return {
...action,
onHandle: async () => {
// Voer eerst de originele publish actie uit
await action.onHandle()
// Stuur notificatie
await fetch('/api/notify-publish', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
documentId: props.id,
title: props.published?.title,
url: props.published?.slug?.current
})
})
}
}
}
return action
})
}
}
```
**Aanvullende bestanden nodig:**
1. **API Route voor notificaties** (`/api/notify-publish.js`):
```javascript
export default async function handler(req, res) {
if (req.method === 'POST') {
const { documentId, title, url } = req.body
// Implementeer je notificatielogica hier (email, Slack, etc.)
console.log(`Document gepubliceerd: ${title} (${url})`)
// Voorbeeld: Slack webhook
/*
await fetch(process.env.SLACK_WEBHOOK_URL, {
method: 'POST',
body: JSON.stringify({
text: `📢 Nieuw document gepubliceerd: *${title}*\nURL: ${url}`
})
})
*/
res.status(200).json({ success: true })
}
}
```
2. **Environment variabelen** (`.env.local`):
```
SANITY_PROJECT_ID=je_project_id
SANITY_DATASET=production
SLACK_WEBHOOK_URL=je_slack_webhook_url
```
**Belangrijke features:**
- ✅ Verplichte titel validatie
- ✅ Unieke URL validatie met real-time checks
- ✅ Automatische notificaties bij publicatie
- ✅ Ondersteuning voor draft documents
- ✅ Aanpasbare notificatiekanalen
**Installatie stappen:**
1. Plaats de code in je schema definitie
2. Maak de API route aan
3. Configureer environment variabelen
4. Pas de notificatiemethode aan naar wens
Wil je dat ik specifieke onderdelen aanpas of uitbreid?