Skip to content

Instantly share code, notes, and snippets.

@amcdnl
Last active February 28, 2016 12:41
Show Gist options
  • Save amcdnl/f14cbfc3738668457ebb to your computer and use it in GitHub Desktop.
Save amcdnl/f14cbfc3738668457ebb to your computer and use it in GitHub Desktop.
define(['angular'], function(angular){
var module = angular.module('utils.cache', ['restmod')
// Cache implementation for angular-restmod
// https://github.com/platanus/angular-restmod/issues/27
module.factory('CacheModel', function(restmod){
var mixin = restmod.mixin(function() {
var cache = {};
// Cache overrides
// ------------------------------------------------------------
this.classDefine('$fetch', function() {
var url = this.$url(),
cached = cache[this.$url()];
if(cached){
return cached;
} else {
return cache[url] = this.$super.apply(this, arguments);
}
});
this.classDefine('$find', function(_pk) {
var url = this.$urlFor(_pk),
cached = cache[url];
if(cached){
return cached;
} else {
return cache[url] = this.$super.apply(this, arguments);
}
});
// set a pointer for cache
this.classDefine('$cache', cache);
});
return mixin;
});
return module;
});
@iobaixas
Copy link

Ups, didn't see that last question, about that, I just realised that the README is missing provider usage directions, you can set a base model in the config stage like this:

module.config(function($restmodProvider) {
  $restmodProvider.pushModelBase(function() { // Dont really like the name for this method, any thoughs?
    this.disableRenaming():
  });
});

About the new implementation, I will miss the local storage support... Why aren't you caching single $fetch results?

@kenjiqq
Copy link

kenjiqq commented Aug 16, 2014

To return results from $search when doing a $find with an id $search returned you could do something like

this.on('after-fetch-many', function(xhr){
  cache[this.$url()] = this;
  angular.forEach(this, function(record) {
    cache[record.$url()] = record;
  });
});

@amcdnl
Copy link
Author

amcdnl commented Aug 18, 2014

@kenborge - Ya I thought about something like that. Managing the list(s) and singles together gets tricky.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment