jmdobry / angular-cache

angular-cache is a very useful replacement for the Angular 1 $cacheFactory.
http://jmdobry.github.io/angular-cache
MIT License
1.39k stars 156 forks source link

Add a .all() method to cache object API #70

Closed roryf closed 10 years ago

roryf commented 10 years ago

This is more of a question really, is there a good reason why the cache object doesn't implement a all() method (or similar) to retrieve all objects? I realise this could be achieved using keys() and iteration, but I'm wondering if it could be implemented better inside the cache.

jmdobry commented 10 years ago

Are you looking for something like:

myCache.put('apple', { color: 'red' });
myCache.put('banana', { color: 'yellow'});

myCache.values(); // output below

/*
[
  { color: 'red' },
  { color: 'yellow' }
]
*/

or

myCache.put('apple', { color: 'red' });
myCache.put('banana', { color: 'yellow'});

myCache.valueSet();  // output below

/*
{
    "apple": { color: 'red' },
    "banana": { color: 'yellow' }
}
*/

or both?

When you "get" an item I have to update it's "accessed" timestamp, so there isn't really a way to do that for all items at the same time. If I were to implement this, it would end up being an iteration anyway. At most these methods would save people a few lines of code. Is that a good enough reason to create them? What do you think?

roryf commented 10 years ago

Yes, that is what I was thinking but I understand more now the side effects of it. I think it's important that the consumer is aware of these side effects, which isn't really obvious from the suggestion above.

Taking a leaf from redis, what about a get method that took multiple keys? This reinforces that idea that you are actually accessing individual objects, but simplifies the retrieval on a client. Seems a reasonable compromise to me.

myCache.get(myCache.keys());

/*
[
  { color: 'red' },
  { color: 'yellow' }
]
*/

// or

myCache.getSet(myCache.keys());

/*
{
    "apple": { color: 'red' },
    "banana": { color: 'yellow' }
}
*/

Not sure how useful the latter would be, and perhaps getAll might be a better name?

jmdobry commented 10 years ago

Hmm, I like the idea of:

myCache.get( [ 'key1', 'key2' ] );
myCache.get( myCache.keys() );

I can easily make this backwards compatible with the current API.

I think it's plausible that a developer would find themselves with a hash of keys, or at least trying to build a hash of key-value pairs from the cache. getSet is a weird name, and I'm not sure if it should accept an array of keys or a hash of keys.

I'll implement the first change, and hold off on the second for now.

roryf commented 10 years ago

:+1:

jmdobry commented 10 years ago

Closing in favor of #71