#Is my fetching implementation correct?

2 messages · Page 1 of 1 (latest)

sterile bolt
#

Is there anything wrong with my fetch utility code? It doesn't seem to refresh the data. I have set the REVALIDATE_TIME on my .env file which is currently 3600. I wanted to make sure that the new data actually contains data since it gets rate limited sometimes and gives back empty arrays which is why I wanted to keep the old cache as a backup and use it whenever this is the case. I am not sure if I am implementing it correctly


export async function fetchAPI(apiUrl) {
    let response;
    let data;
    let attempts = 0;
    let revalidateTime = process.env.REVALIDATE_TIME

    while (attempts < 3) {
        response = await fetch(process.env.NEWS_API + apiUrl, {
            next: {
                revalidate: revalidateTime
            }
        })

        if (!response.ok) {
            throw new Error(response.statusText)
        } 

        data = await response.json()

        // Check if the data contains only empty arrays
        const isEmpty = Object.values(data).every(value => Array.isArray(value) && value.length === 0);

        if (!isEmpty) {
            // If the data is not empty, cache it and return it
            cache = data;
            return data;
        }

        // If the data is empty and there's cached data, return the cached data
        if (cache) {
            console.log("serving cached data new data is empty")
            return cache;
        }

        // If the data is empty and there's no cached data, wait for 1000ms before the next attempt
        await new Promise(resolve => setTimeout(resolve, 1000));
        attempts++;
    }

    // If there's no cached data after 3 attempts, throw an error
    throw new Error("Data is empty and there's no cached data after 3 attempts");
}

proud bluffBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)