2019-04-13 22:52:58 +02:00
const fs = require ( 'fs' )
2019-11-04 21:59:01 +01:00
const util = require ( 'util' )
2019-04-13 22:52:58 +02:00
const path = require ( 'path' )
const { siteUrl , siteTitle , siteDescription , author } = require ( '../config' )
2019-11-04 21:59:01 +01:00
const writeFile = util . promisify ( fs . writeFile )
2019-04-13 22:52:58 +02:00
const feedContent = edge => {
const { image } = edge . node . frontmatter
const { html } = edge . node
const footer =
'<hr />This post was published on <a href="https://kremalicious.com">kremalicious.com</a>'
return image
? ` <img src=" ${ image . childImageSharp . resize . src } " /><br /> ${ html } ${ footer } `
: ` ${ html } ${ footer } `
}
2019-10-02 15:32:01 +02:00
async function jsonItems ( posts ) {
return await posts . map ( edge => {
2019-04-13 22:52:58 +02:00
const { frontmatter , fields , excerpt } = edge . node
const { slug , date } = fields
return {
id : path . join ( siteUrl , slug ) ,
url : path . join ( siteUrl , slug ) ,
title : frontmatter . title ,
summary : excerpt ,
date _published : new Date ( date ) . toISOString ( ) ,
date _modified : frontmatter . updated
? new Date ( frontmatter . updated ) . toISOString ( )
: new Date ( date ) . toISOString ( ) ,
tags : [ frontmatter . tags ] ,
content _html : feedContent ( edge )
}
} )
2019-10-02 15:32:01 +02:00
}
2019-04-13 22:52:58 +02:00
2019-10-02 15:32:01 +02:00
const createJsonFeed = posts => ( {
version : 'https://jsonfeed.org/version/1' ,
title : siteTitle ,
description : siteDescription ,
home _page _url : siteUrl ,
feed _url : path . join ( siteUrl , 'feed.json' ) ,
user _comment :
'This feed allows you to read the posts from this site in any feed reader that supports the JSON Feed format. To add this feed to your reader, copy the following URL — https://kremalicious.com/feed.json — and add it your reader.' ,
favicon : path . join ( siteUrl , 'favicon.ico' ) ,
icon : path . join ( siteUrl , 'apple-touch-icon.png' ) ,
author : {
name : author . name ,
url : author . uri
} ,
items : jsonItems ( posts )
} )
2019-04-13 22:52:58 +02:00
2019-10-02 15:32:01 +02:00
const generateJsonFeed = async posts => {
2019-04-13 22:52:58 +02:00
await writeFile (
path . join ( './public' , 'feed.json' ) ,
2019-10-02 15:32:01 +02:00
JSON . stringify ( createJsonFeed ( posts ) ) ,
2019-04-13 22:52:58 +02:00
'utf8'
) . catch ( err => {
throw Error ( '\nFailed to write JSON Feed file: ' , err )
} )
// eslint-disable-next-line no-console
console . log ( '\nsuccess Generating JSON feed' )
}
module . exports = { generateJsonFeed , feedContent }