Created
March 26, 2018 08:51
-
-
Save HoverBaum/a4ecf88072d7936beb660eac135d3c21 to your computer and use it in GitHub Desktop.
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
const generateAssetsList = (posts, baseUrl, simpleLog = console.log) => new Promise(async resolve =>{ | |
const apiURL = `${baseUrl.replace(/\/$/, '')}/wp-json/wp/v2/media` | |
simpleLog('Reducing posts to asset numbers') | |
let infosFetched = 0 | |
// First add the featured_media images and get ther URLs. | |
const featuredAssets = await Promise.all(posts.reduce((all, post) => { | |
if (!post.featured_media) return all | |
return all.concat([{ | |
mediaNumber: post.featured_media, | |
postId: post.id | |
}]) | |
}, []) | |
.map(async ({mediaNumber, postId}, i , array) => { | |
const featuredMedia = await getJSON(`${apiURL}/${mediaNumber}`) | |
infosFetched += 1 | |
simpleLog(`Getting info about assets ${infosFetched}/${array.length}`) | |
return { | |
mediaNumber, | |
link: featuredMedia.guid.rendered, | |
title: featuredMedia.title.rendered || `asset${i}`, | |
description: featuredMedia.alt_text || '', | |
postId | |
} | |
// After all this we also add images from the body of posts. | |
})) | |
const assets = featuredAssets.concat(posts.reduce((all, post) => { | |
const images = post.bodyImages ? post.bodyImages : [] | |
return all.concat(images) | |
}, [])) | |
resolve(assets) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment