How to cache query result in ember data

后端 未结 2 467
太阳男子
太阳男子 2020-12-30 19:39

I want to cache the result of a query in ember-data. (findQuery)

To make it clear: I don\'t want to cache the entire models; just what models a

相关标签:
2条回答
  • 2020-12-30 19:53

    I'm not an Ember expert but I think you can address your problem with a pure JS solution.

    Given Ember Data queries return Promises, e.g. return this.store.findAll('blog-post'); // => Promise, we can cache promises in a simple object with higher order functions (functions that return functions). The object cache could be replaced with localStorage, sessionStorage, Map or even WeakMap but I'm using the object cache to make things simple to understand.

    What you want to essentially do is to replace following call:

    return this.store.findAll('blog-post');
    

    with something more or less like:

    return cachedStore.findAll('blog-post');
    

    actually, with the solution below it might look more like:

    return cachedStore.call(this, 'findAll', 'blog-post');
    

    As a result, you will request data once and always return from cache in subsequent calls.

    Let me show you how the implementation might look like:

    var cachedStore = (function () {
      // Your cache - in this case simple object literal
      var cache = {};
    
      // Actual method that will check cache for results before trying to query services
      return function (method) {
        var args = Array.prototype.slice.call(arguments, 1);
        var serializedArgs = JSON.stringify(args);
    
        if (!(serializedArgs in cache)) {
          cache[serializedArgs] = this.store[method].apply(this, args);
        }
        return cache[serializedArgs];
      };
    }());
    

    And here's a sample usage:

    // Fires a request
    cachedStore.call(this, 'findAll', 'blog-post');
    // Returns from cache
    cachedStore.call(this, 'findAll', 'blog-post');
    // Returns from cache
    cachedStore.call(this, 'findAll', 'blog-post');
    
    // Fires a request
    cachedStore.call(this, 'findRecord', 'blog-post', 123);
    // Returns from cache
    cachedStore.call(this, 'findRecord', 'blog-post', 123);
    // Returns from cache
    cachedStore.call(this, 'findRecord', 'blog-post', 123);
    

    Does that help in any way?

    0 讨论(0)
  • 2020-12-30 19:53

    When you fire a request based on params Ember Data doesn't know how those params necessarily translate into the models (aka it doesn't know that you have all of the records that have some sort of relationship param1). You can cache it yourself, but then you'd still need some sort of way of knowing those records from other records in your store.

    0 讨论(0)
提交回复
热议问题