Last active
August 29, 2015 13:57
-
-
Save adamalbrecht/9499022 to your computer and use it in GitHub Desktop.
Simplified CoffeeScript wrappers for my REST API.
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
class BaseAPI | |
constructor: (@route, @options={}) -> | |
# Some extra logic based on @options. Mine involves setting up optional parent routes for nested resources. | |
getList: (params={}) -> | |
# GET request using @route and the params. Returns a promise. | |
get: (id, params={}) -> | |
# GET request using @route, id and params. Returns a promise. | |
update: (updatedResource) -> | |
# PUT request using @route, id and supplied resource. Returns a promise. | |
create: (newResource) -> | |
# POST request using @route and the supplied resource. Returns a promise | |
remove: (resource) -> | |
# DELETE request using @route and the resource's id | |
# $q is Angular's promise library | |
# $cacheFactory is Angular's caching library | |
class CachedAPI extends BaseAPI | |
constructor: (@route, @options={}) -> | |
super(@route, @options) | |
@cache = $cacheFactory("#{@route}-cache", someCacheOptions) | |
# By using promises, it's easy to perform actions upon the response received from the base class | |
# and then forward it along to the subclass. | |
getList: (params) -> | |
d = $q.defer() | |
key = @collectionCacheKey(params) | |
if @cache.get(key) | |
d.resolve(@cache.get(key)) | |
else | |
super(params).then( | |
(list) => | |
@cache.put(key, list) | |
d.resolve(list) | |
(err) -> d.reject(err) | |
) | |
d.promise | |
get: (id, params) -> | |
d = $q.defer() | |
key = @resourceCacheKey(id, params) | |
if @cache.get(key) | |
d.resolve(@cache.get(key)) | |
else | |
super(id, params).then( | |
(resource) => | |
@cache.put(key, resource) | |
d.resolve(resource) | |
(err) -> d.reject(err) | |
) | |
d.promise | |
update: (updatedResource) -> | |
@clearCache() | |
super(updatedResource) | |
create: (newResource) -> | |
@clearCache() | |
super(newResource) | |
remove: (object) -> | |
@clearCache() | |
super(object) | |
clearCache: (key=null)-> | |
if key? | |
@cache.remove(key) | |
else | |
@cache.removeAll() | |
collectionCacheKey: (params) -> | |
_.compact([@route, stringifyParams(params)]).join('_') | |
resourceCacheKey: (id, params=null) -> | |
_.compact([@route, id, stringifyParams(params)]).join('_') | |
class EventsAPI extends CachedAPI | |
constructor: -> | |
super("events", {}) | |
someExtraNonRestfulAction: (params) -> | |
# Get request | |
currentEvents = [] | |
api = new EventsAPI() | |
api.getList().then( | |
(events) -> currentEvents = events | |
(err) -> alert('error!') | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment