Skip to content

Instantly share code, notes, and snippets.

@kmelve
Created August 27, 2018 20:17
Show Gist options
  • Select an option

  • Save kmelve/4f011efe68c4875a821b255de096a0a1 to your computer and use it in GitHub Desktop.

Select an option

Save kmelve/4f011efe68c4875a821b255de096a0a1 to your computer and use it in GitHub Desktop.
This is an example script on how to export content from the Sanity blog schema out to markdown.
/**
* This is an example script on how to export content from
* the blog schemas out to markdown.
*
* Run this script in a Sanity project folder with
* $ sanity exec markdown.js > blogposts.md
* on a public dataset, and
* $ sanity exec --with-user-token markdown.js > blogposts.md
* on a private dataset
*/
import client from 'part:@sanity/base/client'
import toMarkdown from '@sanity/block-content-to-markdown'
import imageUrlBuilder from '@sanity/image-url'
/**
* This function can build an image from
* an asset reference with hotspot and crop
* */
const urlFor = source => imageUrlBuilder(client).image(source)
/**
* We use the project config to resolve images in
* block content
*/
const { projectId, dataset } = client.clientConfig
const { log } = console
const serializers = {/* Custom blocks here */}
function getData(query) {
return client.fetch(query)
}
async function parseToMarkdown(data) {
data.forEach(({
title = '',
_createdAt,
_id,
_rev,
_type,
_updatedAt,
author = undefined,
body = [],
categories = [],
mainImage,
slug
}) => {
/** Output title */
log(`# ${title}`)
/** Byline */
log(`First published: ${new Date(_createdAt).toDateString()} – Updated: ${new Date(_updatedAt).toDateString()}`)
if(author && author.image) log(`![${author.name}](${urlFor(author.image)})`)
if(author && author.name) log(`by ${author.name}`)
log(`\n`)
/** Main blogpost image */
if (mainImage) log(`![](${urlFor(mainImage).url()})`)
/** Rich text with no custom block types */
if (body) log(toMarkdown(body, { projectId, dataset, serializers }))
if (categories) log(`Filed under: ${categories.map(({title}) => title).join(', ')}`)
})
}
(async() => {
const query = `
*[_type == "post"]{
...,
author->,
categories[]->
}
`
const data = await getData(query).catch(console.error)
await parseToMarkdown(data)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment