Skip to content

Instantly share code, notes, and snippets.

@sjlu sjlu/Contentful.js
Last active Jun 3, 2019

Embed
What would you like to do?
This helps compile Jekyll posts from Contentful
var Promise = require('bluebird')
var _ = require('lodash')
var fs = require('fs')
var contentful = require('contentful')
var client = contentful.createClient({
space: '0eybfmw2qkbf',
accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
host: process.env.CONTENTFUL_HOST
})
var contentType = 'post'
var layout = 'post'
var writeFile = Promise.promisify(fs.writeFile)
var unlink = Promise.promisify(fs.unlink)
var mkdir = Promise.promisify(fs.mkdir)
var readdir = Promise.promisify(fs.readdir)
var postsDir = __dirname + '/_posts'
var createPost = function (entry) {
var fields = entry.fields
return Promise
.bind({
title: _.get(fields, 'title'),
slug: _.get(fields, 'slug'),
excerpt: _.get(fields, 'excerpt'),
hero: _.get(fields, 'hero.fields.file.url'),
author_name: _.get(fields, 'author.fields.name'),
author_photo: _.get(fields, 'author.fields.photo.fields.file.url'),
date: _.get(fields, 'date'),
categories: _.get(fields, 'categories'),
body: _.get(fields, 'body')
})
.then(function () {
var filename = [
this.date,
this.slug
].join('-')
var post = [
'---',
'layout: ' + layout,
'title: ' + this.title,
'author_name: ' + this.author_name,
'author_photo: ' + this.author_photo,
'date: ' + this.date + ' 09:00:00 -500',
'categories: ' + JSON.stringify(this.categories),
'image: ' + this.hero,
'excerpt: ' + this.excerpt,
'published: true',
'---',
'',
this.body
].join('\n')
return writeFile(postsDir + '/' + filename + '.md', post)
})
}
var createDir = function (dir) {
return Promise
.resolve(mkdir(dir))
.catch({ code: 'EEXIST' }, function () {})
}
var cleanDir = function (dir) {
return Promise
.resolve(readdir(dir))
.map(function (file) {
return unlink(dir + '/' + file)
})
}
Promise
.bind({})
.then(function () {
return createDir(postsDir)
})
.then(function () {
return cleanDir(postsDir)
})
.then(function () {
return client.getEntries({
content_type: contentType
})
})
.then(function (resp) {
return resp.items
})
.map(function (entry) {
return createPost(entry)
})
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.