Ember-Data .find() vs .all() - how to control cache?

后端 未结 2 497
走了就别回头了
走了就别回头了 2021-02-02 12:10

I was told that in order to not make a request all the time, one can use .all() method to load data that is kept in the store. But how does Ember deal with cache? I have a coupl

相关标签:
2条回答
  • 2021-02-02 12:46

    What you call cache is the content of the store. There are usually 2 ways to update the store to reflect changes made on the backend side:

    • the change happens with a user interaction/call to the server. If you update mulitple records on the backend side, you can sideload them with the response of that request.
    • the change happens asynchronously on the backend side (background job). You can use a websocket to push those changes to the client.
    0 讨论(0)
  • 2021-02-02 12:49

    So will start by answering question from your comment:

    I'd rather to know how can I load data when an app starts (not via routes as I don't have to update it so often). Is it possible

    So OK technically this is still via routes, but the best way to load data when an app "starts" is via the Application Route's model hook.

    App.ApplicationRoute = Ember.Route.extend({
      model: function({
        return App.Post.find();
      })
    })
    

    The router will wait for promise returned by find() to resolve, so you can be sure that response from server has come back before any other routes are entered.

    How do you control cache?

    Mostly you don't worry about it. You can refresh() an individual record after some timeout if needed.

    When do you use .find() and when .all(). Do you use .find() and then .all()? For how long?

    Depends what you want to achieve. In our app we use find() in the application route, then either all() or a filter() in other routes.

    Does .all() have some expiration date so that after some time it can make a new request?

    Nope. It will never make a new request

    Or it uses Local Storage so that I have to clear it manually?

    It does not use local storage, records are in memory. So for sure an F5 will clear the cache.

    Suppose that I have some data I'd like to refresh only once a week? How should I go about this? Now every time I enter or re-visit the same route a new request is made. How can I avoid this?

    So OK let's assume you use find() only in the application route, and that user keeps browser open for 1 week and the records have expired. There are many ways to refresh, what's easy/best depends on if they all expire at once or if they time-out one at a time.

    • Have some timer checks for expired records and calls refresh() as needed.
    • Have a Ping model that you update on some schedule. When server responds to update it can sideload any changed records.
    • Or can just refresh the browser once per week (via window.location...)
    0 讨论(0)
提交回复
热议问题