Search code examples
javascriptjqueryajaxreddit

Proper repeat of API access


I'd like to create a live feed for the front page of Reddit by the use of the API. Since it has very limited support for Websocket, I thought I'd use a sub-optimal solution: my program would get the most recent posts with a certain frequency and append some data of them to an HTML table.

To provide some code, here's a shortened version of what I'm doing:

//cliendID and clientSec are declared vars I omit for safety reasons
function Auth(callback){

  //Authorization to Reddit API
  $.ajax({
      type: 'POST',
      url: "https://www.reddit.com/api/v1/access_token",

      beforeSend: function(xhr) {
        xhr.setRequestHeader(
               "Authorization", 
               "Basic " + btoa(clientID + ":" + clientSec));
      },

      data:
        {
          grant_type: "client_credentials",
          user: clientID,
          password: clientSec
        },

      success: callback
  });
}

//params.listing and APIurl are also declared
function afterAuth(token){
    accessAPI(token, printResult, params.listing, APIurl);
}


//standardized Reddit API access
function accessAPI(response, callback, inputJSON, url){

  //console.log("accessAPI: "+response);

  $.ajax({
      type: 'GET',
      url: /* an oauth.reddit.com link */,

      beforeSend: function(xhr) {
        xhr.setRequestHeader("Authorization", response.token_type + " " + response.access_token);
      },

      data: /* input necessary for that API request */

      success: callback
  });

};

//test function, for demonstration purposes
function printResult(querydat){
  console.log(querydat);
}

What my program does is a simple call: Auth(afterAuth), where the chain follows:

  • The POST AJAX request within Auth, if successful, calls afterAuth.

  • afterAuth uses an identification token (if I remember correctly) as an input and functions as a "wrapper" to be able to run multiple API accesses.

  • In this example, accessAPI is used for a GET AJAX request which directly accesses an oauth.reddit.com link, from which it fetch subreddit data.

  • I manipulate this data through its success callback, which, here, is a simple demo function.


What I want to achieve is the periodic call of accessAPI so that it runs its callback on more recent posts as time goes on.

Because of the asynchronous nature of these calls (I presume), neither setInterval nor looped setTimeout seems to be a viable solution.

What else can I do to produce this periodic call?

(needless to say, repeated call of Auth() is impractical, but I can't see, how can I manipulate the inner flow otherwise.)


Solution

  • I could find a solution meanwhile.

    The key was adding some "flow control" into accessAPI by using a plus input, repeat.

    The AJAX call itself is now in a different function within the scope of accessAPI, so setInterval repeats the separate function.

    function accessAPI(access_token, callback, inputJSON, url, repeat){
    
    
        if(repeat==0){ accessAPI_Execute();
                }else{ setInterval(accessAPI_Execute, repeat*1000)};
    
    
        //local function for setInterval() control
        function accessAPI_Execute(){
    
            //console.log("sending request...");
    
            $.ajax({
                type: 'GET',
                url: url,
    
                beforeSend: function(xhr) {
                xhr.setRequestHeader("Authorization", access_token.token_type + " " + access_token.access_token);
                },
    
                data: inputJSON,
    
                success: callback
            })
        };
    
    };
    

    Unless any better solution comes, I consider it the accepted one.