Skip to content

Instantly share code, notes, and snippets.

@beppek
Last active February 5, 2023 00:48
Show Gist options
  • Save beppek/54d7ef592798a77ee6928b6dff2af689 to your computer and use it in GitHub Desktop.
Save beppek/54d7ef592798a77ee6928b6dff2af689 to your computer and use it in GitHub Desktop.
Example of how to query multi level nested documents in Sanity
import { FcTreeStructure } from 'react-icons/fc';
export default {
name: 'category',
title: 'Category',
type: 'document',
icon: FcTreeStructure,
fields: [
{
name: 'title',
title: 'Title',
type: 'string',
},
{
name: 'description',
title: 'Description',
type: 'text',
},
{
name: 'child',
title: 'Child Category',
type: 'array',
of: [{ type: 'reference', to: [{ type: 'category' }] }],
},
],
preview: {
select: {
title: 'title',
},
},
};
const sanityClient = require('@sanity/client');
const groq = require('groq');
const fs = require('fs');
const prettier = require('prettier');
function getMultiLevelCategoryQuery(index, max) {
const childQuery = index < max ? getMultiLevelCategoryQuery(index + 1, max) : '...';
return `
title,
"products": *[_type=='product' && references(^._id)]{ title },
child[]->{
${childQuery}
}
`;}
async function getMultiLevelCategories(client) {
const query = groq`
*[_type == "category" && title == "Level 1"] {
${getMultiLevelCategoryQuery(0, 10)}
}
`;
const data = await client.fetch(query);
return data;
}
const options = {
dataset: '<your-dataset>',
projectId: '<your-project-id>',
useCdn: false, // just a demo so no need for cdn obv
};
const client = sanityClient(options);
module.exports = (async () => {
const [categories, prettierConfig] = await Promise.all([
getMultiLevelCategories(client),
prettier.resolveConfig('./.prettierrc.js'), // get your local prettier config to make pretty formatting
]);
const formatted = prettier.format(JSON.stringify(categories), {
...prettierConfig,
parser: 'json',
});
fs.writeFileSync('./demo.json', formatted);
})();
import { FcTreeStructure } from 'react-icons/fc';
export default {
name: 'product',
title: 'Product',
type: 'document',
icon: FcTreeStructure,
fields: [
{
name: 'title',
title: 'Title',
type: 'string',
},
{
name: 'description',
title: 'Description',
type: 'text',
},
{
name: 'category',
title: 'Category',
type: 'array',
of: [{ type: 'reference', to: [{ type: 'category' }] }],
},
],
preview: {
select: {
title: 'title',
},
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment