Created
August 1, 2013 13:40
-
-
Save josephwegner/6131425 to your computer and use it in GitHub Desktop.
AngularJS API Service
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
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