Skip to content

Instantly share code, notes, and snippets.

@dblodorn
Created January 25, 2023 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dblodorn/b203fd8e6c18777c6bc941f3dc42e1c8 to your computer and use it in GitHub Desktop.
Save dblodorn/b203fd8e6c18777c6bc941f3dc42e1c8 to your computer and use it in GitHub Desktop.
Flatten Sanity Post to Text nextjs api route example
import type { NextApiRequest, NextApiResponse } from 'next'
import {
getClient,
postQuery,
SanityPostQueryProps,
} from '../../../lib/sanity'
const blogPostHandler = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
const { slug } = req.query
const { post }: SanityPostQueryProps = await getClient(false).fetch(
postQuery,
{
slug: slug,
}
)
const cleanedPostContent = post?.content.map((item: any) => {
if (item?._type === 'block') {
return item.children.map((child: any) => { return child?.text })
}
}).flat()
return res.status(200).json({
slug: slug,
content: cleanedPostContent.length && cleanedPostContent.toString(),
post: post?.content,
})
}
export default blogPostHandler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment