Created
June 13, 2014 11:23
-
-
Save leecrossley/18b0a64aa36319c5dd11 to your computer and use it in GitHub Desktop.
Data HTTP request with localStorage cache (and expiry)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var data = (function () { | |
var data = {}; | |
var mins = 5; | |
var baseUrl = "http://.../api/"; | |
data.get = function (key, successCb, errorCb) { | |
var raw = JSON.parse(localStorage.getItem(key)); | |
if (!raw || !raw.expiry || new Date().getTime() >= raw.expiry) { | |
getFromApi(key, successCb, errorCb); | |
return; | |
} | |
successCb(JSON.parse(raw.val)); | |
}; | |
var persist = function (key, val) { | |
localStorage.setItem(key, JSON.stringify({ | |
val: JSON.stringify(val), | |
expiry: new Date().getTime() + (mins * 60 * 1000) | |
})); | |
}; | |
var getFromApi = function (key, successCb, errorCb) { | |
var uri = baseUrl + key; | |
var request = new XMLHttpRequest(); | |
request.open("GET", uri, true); | |
request.onload = function () { | |
if (request.status >= 200 && request.status < 400) { | |
var val = JSON.parse(request.responseText); | |
persist(key, val); | |
successCb(val); | |
} else { | |
errorCb(); | |
} | |
}; | |
request.onerror = errorCb; | |
request.send(); | |
}; | |
return data; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment