Giacomo Balli profile picture
Giacomo Balli
Your Technology Advisor

Over two decades of experience at your service.
I help small business owners make better decisions.

Let's Chat LinkedIn

Cache API Calls

This code sample will allow you to cache API calls for a super fast UX.

function makeApiCall(url, cbk, apiCallneedsRefresh, args) {
   if (localStorage.getItem("apiResp-" + url) && !apiCallneedsRefresh && (!args || JSON.stringify(args) == "{}")) {
        console.log("Will use cached " + url + " API response.");
        var resp = JSON.parse(localStorage.getItem("apiResp-" + url));
        cbk(resp);
        return;
    }
    var req = new XMLHttpRequest();
   	if (args) {
        req.args = args;
        req.open("POST", url, true);
        //req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        req.setRequestHeader("Content-type", "application/json");
    } else {
        req.open("GET", url, true);
    }
    req.url = url;
    req.onerror = function (e) {
        var errMsg="";
        if (e.position === 0 && e.totalSize === 0) {
           	errMsg="No connection ☹";
        } else {
            errMsg="API Error

" + JSON.stringify(e) + "
" + req.status + " - " + req.statusText; } alert(errMsg); console.log("API Error
" + JSON.stringify(e)); }; req.onload = function (evt) { if (req.status === 404) { alert("Whoops, something went wrong.
Resource not found."); return; } else if (req.status === 401) { alert("Unauthorized."); return; } else if (req.status === 500) { alert("Currently unavailable: server error"); return; } var resp = JSON.parse(evt.target.responseText); cbk(resp); if (!args) { localStorage.setItem("apiResp-" + url, evt.target.responseText); console.log("Api call to " + url + " cached.", resp); } else { console.log("Api call to " + url + " completed.", args, resp); } }; req.send(JSON.stringify(args)); }

Directions:
- url is the full url you want to retrieve.
- cbk is the callback function to be executed when a response is received.
- apiCallneedsRefresh is a boolean variable to force a fresh call.
- args is a JSON object to be POSTed.
- sample usage: makeApiCall("http://google.com/API/search", function(r){console.log(r);}, true, {name:"John",last_name:"Doe"});

Note:
This snippet focuses on iOS development. Make sure to verify/adapt any vendor prefixes. Back to main listing.

Published: Sun, Jan 10 2016 @ 18:23:03
Back to Blog