Created
March 22, 2016 10:10
-
-
Save jordinebot/2976dc34f7769457b9b1 to your computer and use it in GitHub Desktop.
API Caller
This file contains hidden or 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
class API | |
constructor: (url) -> | |
@url ?= apiURL | |
@status = | |
OK: 200, | |
DONE: 4 | |
@cache = {} | |
@cacheExpiration = 0 #seconds | |
call: (query, callback) => | |
query ?= '' | |
callback ?= () => | |
console.log 'Error: No callback' | |
if not @cache[encodeURIComponent query]? or @.isExpired query | |
xhr = new XMLHttpRequest() | |
xhr.open 'GET', (@url + query), true | |
xhr.onreadystatechange = @.processResponse xhr, query, callback, arguments[2] | |
xhr.send() | |
else | |
callback @cache[encodeURIComponent query].data, arguments[2] | |
isExpired: (query) -> | |
now = new Date().getTime() | |
((now - @cache[encodeURIComponent query].time) / 1000) > @cacheExpiration | |
processResponse: (xhr, query, callback, param = null) => | |
() => | |
if typeof callback is 'function' | |
if xhr.readyState is @status.DONE and xhr.status = @status.OK | |
@cache[encodeURIComponent query] = | |
data: JSON.parse xhr.responseText | |
time: new Date().getTime() | |
callback (JSON.parse xhr.responseText), param |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment