Syl
Syl

Reputation: 3829

How to retrieve the same model from another REST url in EmberJS

The models tree of my emberJS app match the tree of my API however, I have 2 different routes returning the same type of data :

/products/ and /users/:id/supported_products/ both return products data.

When I need to have the products of the app there is no problem :

 this.store.query('product',params);

However I am not sure how to query products from the user path. The place to do so would be the adapter, but I need to define a secondary adapter that I would call when I need supported products,and I have no idea how to do so.

Upvotes: 0

Views: 201

Answers (1)

Sukima
Sukima

Reputation: 10084

I think if it were me I would create a virtual query parameter that would instruct a custom adapter on how to change the endpoint on the fly.

For example I might have a supportedByUser flag. Then in my app/adapters/product.js do something like this:

import JSONAPIAdapter from 'ember-data/adapters/json-api';
export default JSONAPIAdapter.extend({
  urlForQuery(query, modelName) {
    let userId = query.supportedByUser;
    delete query.supportedByUser;
    return userId
      ? `${this.namespace || ''}/users/${userId}/supported_products`
      : this._super(...arguments);
  }
});

Here is an example twiddle demoing this: https://ember-twiddle.com/b406391e98ed4fda30bc227a894fa7c9

Upvotes: 3

Related Questions