Skip to content

Instantly share code, notes, and snippets.

@8bitme
Forked from gbabiars/ghost-to-gatsby.js
Last active May 4, 2018 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 8bitme/2b5d38bf5864eb454598d36967f71e49 to your computer and use it in GitHub Desktop.
Save 8bitme/2b5d38bf5864eb454598d36967f71e49 to your computer and use it in GitHub Desktop.
A script to migrate posts from Ghost's exported json to Gatsby
const fs = require('fs');
const path = require('path');
const moment = require('moment');
const json = require('./8bitzen.ghost.2018-04-28.json');
const post_tags = json.db[0].data.posts_tags;
const tags = json.db[0].data.tags;
function ensureDirectoryExistence(filePath) {
var dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}
json.db[0].data.posts
.filter(p => p.status === 'published')
.forEach(({
id,
title,
slug,
published_at: published,
mobiledoc
}) => {
const date = moment(published).format('YYYY-MM-DD');
const markdown = JSON.parse(mobiledoc).cards[0][1].markdown;
const associatedTags =
'[' +
post_tags
.filter(t => t.post_id === id)
.map(t => {
const associatedTag = tags.find(tag => tag.id === t.tag_id);
return `"${associatedTag.name}"`;
})
.reduce(
(accumulator, currentValue) => `${currentValue},${accumulator}`
) +
']';
const content = `---
title: "${title.replace (/\:\n/)}"
date: "${date}"
tags: ${associatedTags}
author: John Smith
publish: true
---
${markdown}
`;
const dir = path.join(__dirname, `/pages/${date}-${slug}`);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
fs.writeFileSync(
path.join(__dirname, `/pages/${date}-${slug}/index.md`),
content
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment