How to Implement Caching || Game of Thrones Api

I am playing around with Game of thrones Api - .

The documentation mentions they are implementing rate limiting. Hence implementing cache is important.

Let's say I want to print all the names of the houses from the Api on a button click

 function getAllHouseNames() {
   for (let i = 1; i <= 45; i++) {
     getHouseNames(i)
    }
  }

async function getHouseNames(page) {
  var req = new XMLHttpRequest();

  req.onreadystatechange = await
  function() {
    if (this.readyState == 4 && this.status == 200) {
      //console.log(req.getResponseHeader("link"));
      let houseObj = JSON.parse(this.responseText);
      for (let i = 0; i < houseObj.length; i++) {
        let p = document.createElement("p");
        let name = document.createTextNode(houseObj[i].name);
        p.appendChild(name);
        document.body.appendChild(p);
      }
    }
  };
  req.open("GET", "" + page + "&pageSize=10", true);
  req.send();
};

Around 45 requests are fired (Since there are 45 pages with information about houses).

How do i implement caching technique in this scenario?

3

1 Answer

Create a global/module level variable. In the code below, I called it cache. then add the properties to it when you have retrieved them. then they are available for later use.

<!doctype html>
<head>
    <title>A Song of Ice and Fire</title>
<!-- include jQuery -->
<script src=""></script>
<script>
var cache = {}; // create a new object for the cache
$(document).ready(function() {
    // once the page is loaded, register a click listener on the button
    $("#btn-get-house-names").on("click", getAllHouseNames);
});

function getAllHouseNames() {
    // if the cache object doesn't have 
    // a property called "houseNames", go ajax
    // otherwise just display the house names in the document
    if (!cache.houseNames) {
        $("#div-house-names").html("Getting House Names");
        getHouseNamesAjax()
    } else {
        $("#div-house-names").html("");
        $.each(cache.houseNames, function(index, houseName) {
            $("#div-house-names").append("<p>" + houseName + "</p>");
        });
    }
}

function getHouseNamesAjax(page) { // use jQuery to ajax
    let pageId = "";
    let pageSize = "pageSize=10";
    if (page) {
        pageId = "?page=" + page + "&" + pageSize;
    } else {
        pageId = "?" + pageSize;
    }

    $.ajax({
        type: "GET",
        url: "" + pageId,
        dataType: "json",
        success: function(data, textStatus, request) {
            if (!cache.houseNames) { // add the houseNames array to the cache object
                cache.houseNames = [];
            }
            $.each(data, function(index, house) {
                cache.houseNames.push(house.name); // append to the end of the array
            });
            if (request.getResponseHeader("link")) { // this looks to see if there is another page of house names
                let headerLinks = request.getResponseHeader("link").split(",");
                let hasNext = false;
                $.each(headerLinks, function(index, headerLink) {
                    let roughLink = headerLink.split("; ")[0];
                    let roughRel = headerLink.split("; ")[1];
                    let rel = roughRel.substring(5, roughRel.length - 1);
                    if (rel == "next") {
                        let pageNum = roughLink.split("?page=")[1].split("&page")[0];
                        getHouseNamesAjax(pageNum);
                        hasNext = true;
                        return false; // break out of $.each()
                    }
                });
                if (!hasNext) { 
                    // if no more pages of houseNames, 
                    // display the house names on the page.
                    // We have to do this here, because ajax is async
                    // so the first call didn't display anything.
                    getAllHouseNames();
                }
            }
        },
        error: function(data, textStatus, request) {
            alert(textStatus);
        }
    });
};
</script>
</head>
<body>
<input type="button" id="btn-get-house-names" value="Get House Names"/>
<div id="div-house-names"> <!-- house names -->
</div>
</body>
</html>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest