Skip to content

Instantly share code, notes, and snippets.

@jordinebot
Created March 22, 2016 10:10
Show Gist options
  • Save jordinebot/2976dc34f7769457b9b1 to your computer and use it in GitHub Desktop.
Save jordinebot/2976dc34f7769457b9b1 to your computer and use it in GitHub Desktop.
API Caller
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