1
votes

I just switched my application over to Ember CLI and Ember-Data (previously using Ember Model). When I transition to my employees route ember data does a GET request on the api's user route with a query as intended. However, whenever I leave this route and return it continues to perform a GET request on the api. Shouldn't these results be cached? I had a filter running on the model, but I removed it and still ran into the same issue.

Route w/ Filter:

import Ember from 'ember';

export default Ember.Route.extend({
    model: function() {
        // This queries the server every time I visit the route
        return this.store.filter('user', {type: 'employee'}, function(user) {
            if(! Ember.isEmpty(user.get('roles'))) {
                return user.get('roles').contains('employee');
            }
        });
    }
});

Route w/out Filter:

import Ember from 'ember';

// This still queries the server every time I visit the route
export default Ember.Route.extend({
    model: function() {
        return this.store.find('user');
    }
});
1

1 Answers

2
votes

Passing a second parameter into the filter function, {type: 'employee'}, turns it into a findQuery + filter, and find will always execute a query request. If you want to only call a particular resource once per SPA lifetime in a particular route you can add logic to keep track of it. The basic concept goes like this:

  1. Check if you've fetched before
  2. If you haven't fetch the records
  3. Save the fetched records
  4. return the saved fetched records

Example

export default Ember.Route.extend({
    model: function() {
        //resultPromise will return undefined the first time... cause it isn't defined
        var resultPromise = this.get('resultPromise') || this.store.find('user');
        this.set('resultPromise', resultPromise);
        return resultPromise;
    }
});

Additionally if you've already called find you can also just use store.all('type') to get all of the records for that type in the store client side without making a call to the server.