How To Implement Caching || Game Of Thrones Api
I am playing around with Game of thrones Api - https://anapioficeandfire.com/Documentation. The documentation mentions they are implementing rate limiting. Hence implementing cach
Solution 1:
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="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></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: "https://www.anapioficeandfire.com/api/houses" + 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>
Post a Comment for "How To Implement Caching || Game Of Thrones Api"