Skip to content

Instantly share code, notes, and snippets.

@cryptoskillz
Created June 22, 2021 05:27
Show Gist options
  • Save cryptoskillz/59a11ec09f521274f5971cdee4da695e to your computer and use it in GitHub Desktop.
Save cryptoskillz/59a11ec09f521274f5971cdee4da695e to your computer and use it in GitHub Desktop.
Our frontend websites are simple flat HTML files created in a JAM stack fashion we recently moved Strapi as our back end CMS and it saves assets images in an uploads directory. We wanted to be able to render these images out of content blocks and repurpose them in our static sites without having to call the API each time
//API Data preprocessing can happen here
const superagent = require('superagent');
let env = require('./env')
//this function gets some date from and API which can be used in the data processing, for simpluicty stakes it is connection to our auctions endpoint so you can see
//it in action
let getSomething = async () => {
try {
var res = await superagent.get(env.API_URL+ "blog-articles/").query({})
//check we got a response.
if (res.ok) {
//console.log(res.body)
let articles = res.body;
for (var i = 0; i < articles.length; i++) {
const regex = /uploads\/(.*)\)/gm;
const str = articles[i].content;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
//console.log(`Found match, group ${groupIndex}: ${match}`);
//check it has been matched correctly
if(match.indexOf("uploads") == -1) {
//console.log(`fetching it ${match}`);
//now you know the location of the image you can pull it down and save it, move it to your cdn or whatever else you want to do with it.
//example to fetch it.
let strapimageUrl = "http://strapidemourl.com/uploads/"
image = file_get_contents(strapimageUrl+match);
//save the image to your static asset dir and eleventy will move it accross
}
//console.log(match)
});
}
}
return res.body;
}
} catch (err) {
console.log('Error getting something:')
console.error(err)
}
}
module.exports = async () => {
let functionResults = [];
if (functionResults.length === 0) functionResults = await getSomething();
//console.log(functionResults)
return {
articlesArray: functionResults
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment