Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creating blogposts in Contentful.
const createBlogPosts = async (posts, assets, categories, managementToken, spaceId, simpleLog = console.log) => {
const client = contentful.createClient({
accessToken: managementToken,
logHandler: (level, data) => simpleLog(`${level} | ${data}`)
})
const space = await client.getSpace(spaceId)
const linkMap = new Map()
assets.forEach(asset => linkMap.set(asset.wpAsset.link, asset.fields.file['en-US'].url))
return Promise.all(posts.map(post => new Promise(async resolve => {
const cmsHeroImageAsset = assets.find(asset => asset.wpAsset.mediaNumber === post.featured_media)
const heroImageId = cmsHeroImageAsset.sys.id
const cmsCategory = categories.find(category => category.wpCategory.categoryNumber === post.category)
const categoryId = cmsCategory.sys.id
let cmsPost
try {
cmsPost = await space.createEntry('blogPost', {
fields: {
title: {
'en-US': post.title
},
body: {
'en-US': replaceWPWithContentfulLinks(post.body, linkMap)
},
slug: {
'en-US': post.slug
},
publishDate: {
'en-US': post.publishDate
},
heroImage: {
'en-US': {
sys: {
type: 'Link',
linkType: 'Asset',
id: heroImageId
}
}
},
category: {
'en-US': {
sys: {
type: 'Link',
linkType: 'Entry',
id: categoryId
}
}
}
}
})
} catch(e) {
throw(Error(e))
}
try {
await cmsPost.publish()
} catch(e) {
throw(Error(e))
}
resolve(cmsPost)
})))
}
const replaceWPWithContentfulLinks = (text, linkMap) => {
let replacedText = text
linkMap.forEach((newUrl, oldUrl) => {
replacedText = replacedText.replace(oldUrl, newUrl)
})
return replacedText
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.