Search code examples
ember.jsember-datathrottling

Throttling Ember Data requests


I’m using Ember Data to interact with a REST API that has a rate limit.

Any suggestions for how to go about throttling Ember Data requests to X requests per second?


Solution

  • First, if you want to do things with all AJAX requests I strongly recommend ember-ajax. This gives you a single point to modify all your AJAX requests. Next about throttling. I suggested ember-concurrency In the comments, so let me elaborate this. ember-concurrency gives you a timeout method, that returns a promise that will resolve after a certain amount of time. This allows easy throtteling:

    export default AjaxService.extend({
      ajaxThrottle: task(function * (cb) {
        cb();
        // maxConcurrency with timeout 1000 means at maximum 3 requests per second.
        yield timeout(1000);
      }).maxConcurrency(3).enqueue(),
      async request() {
        await new Promise(cb => ajaxThrottle.perform(cb));
        return this._super(...arguments); // this should make the actual request
      },
    });