Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retry based on body content #860

Closed
Zeranoe opened this issue Aug 21, 2019 · 3 comments
Closed

Retry based on body content #860

Zeranoe opened this issue Aug 21, 2019 · 3 comments

Comments

@Zeranoe
Copy link

Zeranoe commented Aug 21, 2019

I'd like to retry a request N times with M seconds between each request, based on the response json data. The page returns a 200 status, so the retry isn't being triggered by default. Here is what I have so far:

async function waitTillComplete(name) {
    return await got(`https://api.gfycat.com/v1/gfycats/fetch/status/${name}`, {
        retry: {retries: 5, statusCodes: [200]},
        hooks: {
            afterResponse: [
                (response, retry) => {
                    const body = JSON.parse(response.body);

                    if (body.task != 'complete') {
                        return retry;
                    }

                    return response;
                }
            ]
        }
    });
}

I'm not sure how to force a retry with a 200 status, and any help would be appreciated.

@lselden
Copy link

lselden commented Aug 22, 2019

Why not just wrap in a while statement?

async function waitTillComplete(name) {
    let retries = 0;
    while (retries < 5) {
        retries += 1;
        // note - this won't retry on request failures or error codes, change opts accordingly
        const response = await got(`https://api.gfycat.com/v1/gfycats/fetch/status/${name}`);
        // could use "json" option of got insted to auto-json parse
        const {task} = JSON.parse(response.body);
        if (task == 'complete') {
            return response;
        }
    }
    throw new Error(`Max retries reached for ${name}`);
}

@Zeranoe
Copy link
Author

Zeranoe commented Aug 22, 2019

I was just trying to use the built in retry functionality, but I've been using a loop for now.

@tobenna
Copy link

tobenna commented Sep 13, 2019

In your example, you're not calling the retry function. Should be:

if (body.task != 'complete') {
    return retry();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants