Created
March 16, 2019 16:11
-
-
Save kmelve/6955f890f832ff458ee2dbca36602b8f to your computer and use it in GitHub Desktop.
Convert a post type in Sanity.io to markdown files with frontmatter
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
/* eslint-disable */ | |
const fs = require('fs') | |
const sanityClient = require('@sanity/client') | |
const groq = require('groq') | |
const BlocksToMarkdown = require('@sanity/block-content-to-markdown') | |
const config = { projectId: '<YourID>', dataset: '<DatasetName>', useCdn: true } | |
const client = sanityClient(config) | |
const serializers = { | |
types: { | |
code: props => `\`\`\`${props.node.language}\n${props.node.code}\n\`\`\``, | |
codesandbox: ({node}) => `<iframe src="https://codesandbox.io/embed/${node.id}?fontsize=14" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>`, | |
youtube: ({ node }) => `<iframe width="560" height="315" src="https://www.youtube.com/embed/${node.id}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`, | |
}, | |
marks: { | |
internalLink: props => `![${props.children[0]}](${props.mark.link})` | |
} | |
} | |
async function getDocs() { | |
const filter = '*[_type == "post" && defined(slug)]' | |
const projection = groq`{ | |
_id, | |
_type, | |
"poster": poster.asset->url, | |
title, | |
blurb, | |
slug, | |
text[]{ | |
..., | |
children[]{ | |
..., | |
_type == "internalLink" => { | |
"link": @->slug.current | |
} | |
} | |
} | |
}` | |
const query = [filter, projection].join(' ') | |
const docs = await client.fetch(query) | |
docs.forEach(post => { | |
const { title, blurb, text, slug } = post | |
const content = ` | |
--- | |
layout: post | |
title: "${title}" | |
description: "${BlocksToMarkdown(blurb)}" | |
--- | |
${BlocksToMarkdown(text, { serializers, projectId, dataset })} | |
` | |
const filename = `posts/${post.slug.current}.md` | |
fs.writeFile(filename, content, function(err) { | |
if (err) { | |
return console.log(err) | |
} | |
console.log('The file was saved!', filename) | |
}) | |
}) | |
} | |
getDocs() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nevermind, figured it out! Uploaded here if anyone else if having problems with image export w/ block level content