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
2020-05-08 13:27:40 +02:00
const feedContent = ( edge ) => {
2019-04-13 22:52:58 +02:00
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 ) {
2020-05-08 13:27:40 +02:00
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
2020-07-11 10:29:42 +02:00
const createJsonFeed = async ( posts ) => ( {
2019-10-02 15:32:01 +02:00
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
} ,
2020-07-11 10:29:42 +02:00
items : await jsonItems ( posts )
2019-10-02 15:32:01 +02:00
} )
2019-04-13 22:52:58 +02:00
2020-05-08 13:27:40 +02:00
const generateJsonFeed = async ( posts ) => {
2019-04-13 22:52:58 +02:00
await writeFile (
path . join ( './public' , 'feed.json' ) ,
2020-07-11 10:29:42 +02:00
JSON . stringify ( await createJsonFeed ( posts ) ) ,
2019-04-13 22:52:58 +02:00
'utf8'
2020-05-08 13:27:40 +02:00
) . catch ( ( err ) => {
2019-04-13 22:52:58 +02:00
throw Error ( '\nFailed to write JSON Feed file: ' , err )
} )
console . log ( '\nsuccess Generating JSON feed' )
}
module . exports = { generateJsonFeed , feedContent }