Skip to content

Instantly share code, notes, and snippets.

@elado
Last active August 29, 2015 14:05
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 elado/a6f5f1f8edade63a3b9d to your computer and use it in GitHub Desktop.
Save elado/a6f5f1f8edade63a3b9d to your computer and use it in GitHub Desktop.
Angular Resource - Share all instances of a query across entire app
app = angular.module 'my-app', ['eo-cached-resource-action']
app.factory 'Category', ($resource, cachedResourceAction) ->
Category = $resource "/categories/:id/:action", {id: '@id'}, {
query: { method: 'GET', cache: true, isArray: true }
}
Category.query = cachedResourceAction.wrapArrayAction(Category.query)
Category
# Usage as usual:
$scope.categories = Category.query()
# or
Category.query (categories) ->
$scope.categories = categories
# or
Category.query().$promise.then (categories) ->
$scope.categories = categories
app = angular.module 'eo-cached-resource-action', []
app.factory 'cachedResourceAction', ($q) ->
arrayResult: ->
value = []
value.$resolved = false
deferred = $q.defer()
value.$promise = deferred.promise
value.$$promise = deferred
value
resolveArrayResult: (value, items) ->
value.$resolved = true
value.length = 0
Array::push.apply(value, items)
value.$$promise.resolve(value)
wrapArrayAction: (resourceActionFn) ->
_loading = false
_cachedValue = @arrayResult()
(callback) =>
if _cachedValue.$resolved
_cachedValue.$$promise.resolve(_cachedValue)
else
_cachedValue.$promise.then(callback) if callback
if !_loading
# this happens only once
_loading = true
resourceActionFn (items) =>
_loading = false
@resolveArrayResult(_cachedValue, items)
_cachedValue
# TODO: ability to invalidate cache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment