Is there a way to do this more effectively?

I have some code for an API that I’m making and I need some help so that adding images would be more efficient.

One of the site endpoints are like this:

app.get("/api/v1/twintails", function(req, res) {

const twin = require("./urls/twintail.json")

var tbase = twin.url

var acceptedWebsites =[

tbase.i1,
tbase.i2,
tbase.i3,
tbase.i4,
tbase.i5,
tbase.i6,
tbase.i7,




]; //put the image urls for the twintails images

if ( acceptedWebsites.indexOf() == -1 ) {
 var twinurl = acceptedWebsites[Math.floor(Math.random()*acceptedWebsites.length)];
}
res.status(200)
res.send({ 
 
 url: twinurl

});
});```

The twintail.json file looks like this:

 ```{
 "url" : {
     "i1" : "https://media.publit.io/file/Twintails/1.jpg",
     "i2" : "https://media.publit.io/file/Twintails/2.jpg",
     "i3" : "https://media.publit.io/file/Twintails/3.jpg",
     "i4" : "https://media.publit.io/file/Twintails/4.jpg",
     "i5" : "https://media.publit.io/file/Twintails/5.jpg",
     "i6" : "https://media.publit.io/file/Twintails/6.jpg",
     "i7" : "https://media.publit.io/file/Twintails/7.png"
 }
}

Is there a way where the image url’s autogenerate and I don’t have to add “tbase.i1,” for each url I add in the twintails.json?
Im storing the images using “publit.io”, if you have a solution with another free CDN you can post a link to it. Also, if it’s easier for you, if you have a solution where only .png files work and not both, png & jpg, I would also like to hear that.

Thanks!

It strikes me that each of your URLs is just https://media.publit.io/file/Twintails/{number}.jpg and you want to constrain the maximum of those numbers.

So could you replace this:

var twinurl = acceptedWebsites[Math.floor(Math.random()*acceptedWebsites.length)];

with this:

const imgLimit = 7;
const imgNumber = Math.floor(Math.random()*imgLimit);
var twinurl = "https://media.publit.io/file/Twintails/" + imgNumber + ".jpg";

… and then ditch the JSON file (and the code that reads it) altogether?

P.s. Use triple backticks for code blocks instead of single backticks, to fix your formatting issue :slight_smile:

3 Likes

Thanks! I’ll try it out!