Skip to content

Instantly share code, notes, and snippets.

@kmelve
Last active November 14, 2019 21:29
Show Gist options
  • Save kmelve/100308ab46e4f16ec9b543f2c3b9ae61 to your computer and use it in GitHub Desktop.
Save kmelve/100308ab46e4f16ec9b543f2c3b9ae61 to your computer and use it in GitHub Desktop.
gatsby rss feed + sanity
const PortableText = require('@sanity/block-content-to-html')
const imageUrlBuilder = require('@sanity/image-url')
const { isFuture, parseISO } = require('date-fns')
const clientConfig = require('./client-config')
const {
getBlogUrl,
filterOutDocsPublishedInTheFuture
} = require('./nodeHelpers.js')
const h = PortableText.h
const isProd = process.env.NODE_ENV === 'production'
const imageUrlFor = source => imageUrlBuilder(clientConfig.sanity).image(source)
{
resolve: `gatsby-plugin-feed`,
options: {
query: `
{
site {
siteMetadata {
title
description
siteUrl
site_url: siteUrl
}
}
}
`,
feeds: [
{
serialize: ({ query: { site, allSanityPost = [] } }) => {
return allSanityPost.edges
.filter(({ node }) => filterOutDocsPublishedInTheFuture(node))
.filter(({ node }) => node.slug)
.map(({ node }) => {
const { title, publishedAt, slug, _rawBody } = node
const url =
site.siteMetadata.siteUrl +
getBlogUrl(publishedAt, slug.current)
return {
title: title,
date: publishedAt,
url,
guid: url,
custom_elements: [
{
'content:encoded': PortableText({
blocks: _rawBody,
serializers: {
types: {
code: ({ node }) =>
h(
'pre',
h('code', { lang: node.language }, node.code)
),
mainImage: ({ node }) =>
h('img', {
src: imageUrlFor(node.asset).url()
}),
twitter: ({ node }) =>
h(
'p',
{},
h('a', {
href: node.url,
innerHTML: 'Look at the tweet.'
})
)
}
}
})
}
]
}
})
},
query: `{
allSanityPost(sort: {fields: publishedAt, order: DESC}) {
edges {
node {
_rawExcerpt
_rawBody(resolveReferences: {maxDepth: 10})
title
publishedAt
slug {
current
}
}
}
}
}
`,
output: '/rss.xml',
title: 'Knut Melvær'
// optional configuration to insert feed reference in pages:
// if `string` is used, it will be used to create RegExp and then test if pathname of
// current page satisfied this regular expression;
// if not provided or `undefined`, all pages will have feed reference inserted
}
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment