Created
October 31, 2017 00:05
-
-
Save lwcooper/246a46902e5bc11c151c84f0f69a3612 to your computer and use it in GitHub Desktop.
Get content from Prismic.io for static site generator
This file contains hidden or 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
// You can run this script as part of your build step in your package.json | |
// eg: | |
// ... | |
// "scripts": { | |
// "build": "node get-content.js && hugo" | |
// } | |
// ... | |
var fs = require('fs'); //to access filewrite | |
var toMarkdown = require ('to-markdown'); //to convert HTML to Markdown | |
var request = require("request"); //to request the JSON file from the server | |
var tomlify = require('tomlify'); //to add the frontmatter | |
var Prismic = require('prismic-javascript'); | |
var PrismicDOM = require('prismic-dom'); | |
var apiEndpoint = 'https://lance-cooper.prismic.io/api/v2/documents/search?ref=WcDCnSgAANsf7vI-&q=[[at(document.type,"blog_post")]]'; | |
//Request options | |
var options = { | |
method: 'GET', | |
json: true, | |
url: apiEndpoint | |
} | |
//Request | |
request(options, function (error, response, body) { | |
if (error) throw new Error(error); | |
var obj = body; //The actual JSON from the API | |
console.log("Start converting API to files"); | |
//Split up the JSON response | |
for (var i=0; i< obj.results.length; i++) { | |
const content = obj.results[i]; | |
const date = content.first_publication_date; | |
const title = content.data.title; | |
const htmlBody = content.data.post_content.map(html => | |
html.type === 'paragraph' ? | |
`<p>${html.text}</p>` : | |
'' | |
); | |
const htmlString = htmlBody.join(''); | |
const slug = content.slugs[0]; | |
var markdowntext = toMarkdown(htmlString); //The HTML conversion | |
var obj2 = tomlify({ | |
title | |
}, {delims: true}); //Creating the frontmatter | |
obj2 = obj2 +"\n" + markdowntext; //Putting it all togeter | |
var file = './content/posts/' + slug + '.md'; | |
fs.writeFile(file, obj2, function (err) { //writing it out to the filesystem | |
if (err) { | |
console.error(err); | |
} else { | |
console.log("Done converting API", title); | |
} | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment