Skip to content

Instantly share code, notes, and snippets.

@josephwegner
Created August 1, 2013 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephwegner/6131425 to your computer and use it in GitHub Desktop.
Save josephwegner/6131425 to your computer and use it in GitHub Desktop.
AngularJS API Service
PlanApp.factory 'api', ($http) ->
###
# Factory for handling api resources
###
class APIBuilder
url: "#{window.location.protocol}//#{window.location.host}/api/v0/"
registerModel: (name, extensions) =>
if @[name]?
throw new Error "Cannot create a model with that name"
model = new BaseModel name
for value, key in extensions
model[key] = value
@[name] = model
API = new APIBuilder()
class BaseModel
constructor: (name) ->
@name = name
@cache =
all:
data: false
stale: 0
getAll: (cb, skipCache = false) ->
if not @cache.all.data or Date.now() - @cache.all.stale > (1000 * 60 * 10) or skipCache
$http.get("/api/v0/#{@name}")
.success (data, status, headers, config) =>
@cache.all.data = data
@cache.all.stale = Date.now()
cb?(false, data)
.error (data, status, headers, config) ->
cb?(data)
else
console.log "get from #{@name} cache", @cache.all.data
cb?(false, @cache.all.data)
get: (id, cb, skipCache = false) ->
if not @cache[id]? or Date.now() - @cache[id].stale > (1000 * 60 * 10) or skipCache
$http.get("/api/v0/#{@name}/#{id}")
.success (data, status, headers, config) =>
if not @cache[id]
@cache[id] = {}
@cache[id].data = data
@cache[id].stale = Date.now()
cb?(false, data)
.error (data, status, headers, config) ->
cb?(data)
else
cb?(false, @cache[id].data)
create: (data, cb) ->
$http.post("/api/v0/#{@name}", data)
.success (data, status, headers, config) ->
cb?(false, data)
.error (data, status, headers, config) ->
cb?(data)
API = new APIBuilder()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment