Created
May 30, 2017 14:21
-
-
Save coderbyheart/f5a348f6dda03d5bbc6f20077caa66ab to your computer and use it in GitHub Desktop.
Import jekyll content for contenful
This file contains 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
const glob = require('glob') | |
const fs = require('fs') | |
const parser = require('jekyll-markdown-parser') | |
const contentful = require('contentful-management') | |
const client = contentful.createClient({ | |
accessToken: '…' | |
}) | |
// This API call will request a space with the specified ID | |
client.getSpace('…') | |
.then(space => { | |
const createEntry = (hero, content, abstract, filename) => space.createEntry('post', { | |
fields: { | |
title: {'en-US': content.parsedYaml.title}, | |
slug: {'en-US': content.parsedYaml.permalink}, | |
publicationDate: {'en-US': content.parsedYaml.date || new Date(filename.match(/^2[0-9]{3}-[0-9]{2}-[0-9]{2}/)[0])}, | |
content: {'en-US': content.markdown}, | |
abstract: {'en-US': abstract}, | |
author: {'en-US': {'sys': {'type': 'Link', 'linkType': 'Entry', 'id': '3f0dPd4qJWMqIckWUwcSEK'}}}, | |
hero: {'en-US': {'sys': {'type': 'Link', 'linkType': 'Asset', 'id': hero}}}, | |
} | |
}) | |
.then(entry => { | |
console.log(entry) | |
}) | |
const importFile = f => fs.readFile(f, 'utf-8', (err, markdown) => { | |
const content = parser.parse(markdown) | |
const filename = f.split('/').pop() | |
const abstract = content.parsedYaml.excerpt || content.html.split('</p>').shift().replace(/<[^>]+>/g, '') | |
const images = content.markdown.match(/!\[([^\]]+)\]\(([^\)]+)\)/gm) | |
if (images) { | |
const img = images[0].match(/!\[([^\]]+)\]\(([^\)]+)\)/) | |
const filename = img[2].split('/').pop() | |
const url = /^\.\/uploads/.test(img[2]) ? `https://blog.coderbyheart.com/${img[2]}` : img[2] | |
space.createAsset({ | |
'fields': { | |
'title': { | |
'en-US': img[1] | |
}, | |
'file': { | |
'en-US': { | |
'contentType': 'image/jpeg', | |
'fileName': filename, | |
'upload': url | |
} | |
} | |
} | |
}) | |
.then(asset => createEntry(asset.sys.id, content, abstract, filename)) | |
} else { | |
createEntry('DJtd5QnpG84a022w8iwWE', content, abstract, filename) | |
} | |
}) | |
glob('./_posts/*.md', (err, res) => { | |
res.map(f => importFile(f)) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment