Search code examples
node.jsrecursionoutputgmail-api

recursive function using gmail api returning same result


Following is a recursive function which logs data fetched from a gmail api.

function listAllMessages(auth, nextPageToken = ''){
    const gmail = google.gmail({version: 'v1', auth});
    let options = {
        userId: 'me',
        nextPageToken: nextPageToken,
    }
    gmail.users.messages.list(options, (err, res) => {
        if (err) return console.log("ListAllMessages returned an error" + err);
//        console.log(res.data);
        if(res.data.nextPageToken){
            console.log(res.data.nextPageToken);
            listAllMessages(auth, res.data.nextPageToken);
        }
    })
}

Rather than printing the next page tokens, the function is printing the same page token consecutively. The first call must go without any page token, while the consecutive calls take the token given in the response of the previous call and print the token of the next page. What am I doing wrong and how can I fix it?

Example of required output: token1 token2 token3 . . . tokenN

Example of current output: token1 token1 token1 token1 . . . .


Solution

  • Based on the gmail.users.messages.list api you should make the request with pageToken but instead you use nextPageToken.

    Change your code to this

    function listAllMessages(auth, nextPageToken = ''){
        const gmail = google.gmail({version: 'v1', auth});
        let options = {
            userId: 'me',
            pageToken: nextPageToken,
        }
        gmail.users.messages.list(options, (err, res) => {
            if (err) return console.log("ListAllMessages returned an error" + err);
            if(res.data.nextPageToken){
                console.log(res.data.nextPageToken);
                listAllMessages(auth, res.data.nextPageToken);
            }
        })
    }