Skip to content

Instantly share code, notes, and snippets.

@ivanoats
Created June 17, 2016 18:45
Show Gist options
  • Save ivanoats/e79ebbd711831be2536d1650890055c4 to your computer and use it in GitHub Desktop.
Save ivanoats/e79ebbd711831be2536d1650890055c4 to your computer and use it in GitHub Desktop.
fetch-from-contentful.js
#!/usr/bin/env babel-node
require('dotenv').config()
import contentful from 'contentful'
import fs from 'fs-extra-promise'
// Contentful Config
const apiToken = process.env.CONTENTFUL_DELIVERY_API_TOKEN
const spaceId = process.env.CONTENTFUL_SPACE_ID
const client = contentful.createClient({ accessToken: apiToken, space: spaceId })
async function getEntriesByType (contentType, fields) {
const options = { content_type: contentType, fields }
try {
return await client.getEntries(options)
} catch (error) {
console.log('LegacyPost error: ', error)
return []
}
}
async function renderPost (post) {
try {
return fs.outputFile(
`pages/${post.fields.slug}/index.json`,
JSON.stringify(post, null, 2)
)
} catch (error) {
console.log('Error creating post', error)
return Promise.reject('error')
}
}
async function renderPage (page) {
try {
return fs.outputFile(
`pages/${page.fields.slug}/index.json`,
JSON.stringify(page, null, 2)
)
} catch (error) {
console.log('Error creating page', error)
return Promise.reject('error')
}
}
async function main () {
try {
const posts = await getEntriesByType('legacyPost', { published: true })
const postPromises = posts.items.map(post => renderPost(post))
await Promise.all(postPromises)
const pages = await getEntriesByType('legacyCustomPage', { active: true })
const pagePromises = pages.items.map(page => renderPage(page))
await Promise.all(pagePromises)
} catch (error) { console.log(error) }
}
main()
@andyshora
Copy link

This saved me a bit of time, thanks @ivanoats!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment