laconic.com/src/lib/utils/blog.ts
2022-04-18 09:23:31 -03:00

88 lines
1.9 KiB
TypeScript

import { render } from 'datocms-structured-text-to-plain-text'
import { BlogPostFragment } from 'lib/cms/generated'
export const getPlainTextContent = (post: BlogPostFragment) => {
const children = post?.content?.value.document.children
const filtered = children.filter((block: any) => block.type === 'paragraph')
const textBlocks = []
for (const block of filtered) {
const paragraph = render(block)
textBlocks.push(paragraph)
}
const text = textBlocks.join(' ')
return text ?? ''
}
export const getDescription = (post: BlogPostFragment) => {
let text = getPlainTextContent(post)
const charLimit = 200
text = text.substring(0, charLimit)
let words = text.trim().split(/\s+/)
words = words.splice(0, words.length - 1)
const description = words.join(' ') + '...'
return description
}
export const getSeoTags = (post: BlogPostFragment) => {
const description = getDescription(post)
const filteredMetaTags = post._seoMetaTags.filter((t) => {
if (
t.attributes?.name === 'description' ||
t.attributes?.name === 'twitter:description' ||
t.attributes?.property === 'og:description' ||
t.tag === 'title'
) {
return false
}
return true
})
return [
...filteredMetaTags,
{
content: post.title + ' | Akash Network',
tag: 'title'
},
{
attributes: {
content: description,
name: 'description'
},
content: null,
tag: 'meta'
},
{
attributes: {
content: description,
property: 'og:description'
},
content: null,
tag: 'meta'
},
{
attributes: {
content: description,
name: 'twitter:description'
},
content: null,
tag: 'meta'
}
]
}
export type BlogPostWithMeta = Omit<BlogPostFragment, 'content'> & {
plainTextContent: string
numId: number
}
export type SingleBlogPost = BlogPostFragment & {
description: string
}