Created
January 25, 2023 18:15
-
-
Save dblodorn/b203fd8e6c18777c6bc941f3dc42e1c8 to your computer and use it in GitHub Desktop.
Flatten Sanity Post to Text nextjs api route example
This file contains hidden or 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
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