Skip to content

Instantly share code, notes, and snippets.

@janpauldahlke
Created April 14, 2020 12:47
Show Gist options
  • Save janpauldahlke/4b395c15e24eba126dedca81a9d9e407 to your computer and use it in GitHub Desktop.
Save janpauldahlke/4b395c15e24eba126dedca81a9d9e407 to your computer and use it in GitHub Desktop.
const fs = require('fs');
const path = require('path');
const dirPath = path.join(__dirname + '/data/')
//helpers
//reads all json files
const readFiles = (dir) => {
const returnFiles = [];
fs.readdir(dir, (err, files) => {
if(err) {
console.log(`unable to scan`, err)
}
files.forEach((file) => {
fs.readFile(dir+file, 'utf-8', (err, contents) => {
if(err) console.log(err);
});
})
})
if(!returnFiles) throw e
return returnFiles
}
//jsonify data
const jsonifyDataFiles = (filename) => {
return JSON.parse(filename, 'utf-8');
}
//create contentnodes
const createContents = (contents) => {
try {
if(!Array.isArray(contents) || contents.length < 1)
{
return
}
else {
const contentsResult = new Array();
contents.map( content => {
contentsResult.push(content)
})
return contentsResult
}
} catch(e) {
console.log('We can not creatContents() here. check contents for beeing Array and length >= 1')
}
}
exports.createPages = ({actions: { createPage }}) => {
const files = readFiles(dirPath)
//we can not iterate over this, since its not here yet,
//gatsby lifecycle?
files.forEach(file => {
const jsonPage = jsonifyDataFiles(file);
if(!jsonPage) console.log('err');
console.log('see',jsonPage)
if(jsonPage.type === 'index') {
console.log('creating index pages');
createPage({
path: `/${jsonPage.pageTitle}`,
component : require.resolve('./src/temaplates/indexPage.js')
})
}
if(jsonPage.type === 'content') {
console.log('creating chapter pages');
jsonPage.chapters.forEach(chapter => {
createPage({
path : `/${jsonPage.pageTitle}/${chapter.slug}`,
component : require.resolve('./src/templates/page.js'),
context : {
title: chapter.chapterTitle,
contents: createContents(chapter.contents)
}
})
});
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment