harkl
harkl

Reputation: 901

Ember: how to add params from router to adapter

I'm trying to fetch data from the following URL structure:

${ENV.APP.API_HOST}/api/v1/customers/:customer_orgCode/sites/

I'm using an adapter to shape the request with buildURL with the following files:

// router.js
this.route('sites', { path: 'customers/:customer_orgCode/sites' }, function() {
    this.route('show', { path: ':site_id' });
});

// adapters/site.js
export default ApplicationAdapter.extend({
  buildURL (modelName, id, snapshot, requestType, query) {
    // return `${ENV.APP.API_HOST}/api/v1/customers/${snapshot???}/sites/`;
    return `${ENV.APP.API_HOST}/api/v1/customers/239/sites/`;
  }
}

// routes/sites/index.js
export default Ember.Route.extend({
  model: function() {
    let superQuery = this._super(...arguments),
        org = superQuery.customer_orgCode;
    this.store.findAll('site', org);
  }
});

I'm able to get the customer_orgCode on the model, but unable to pull it into the adapter. I've noted that the model isn't being populated in the Ember inspector, but the sites data is present when I make the request. Does anyone know how I can dynamically populate the buildURL with the customer_orgCode from the params on the router? And then specify sites/index to use the 'site' model?

Upvotes: 3

Views: 1122

Answers (1)

harkl
harkl

Reputation: 901

OK, I've figured this out. I needed to use query() instead of findAll() in the route. This allows buildURL to pickup the query parameter from the route and pass it in as the 5th argument ie. - buildURL(modelName, id, snapshot, requestType, query). Then in the route, I was neglecting return as part of my model setup. So the solution is below for anyone interested.

// router.js
this.route('sites', { path: 'customers/:customer_orgCode/sites' }, function() {
    this.route('show', { path: ':site_id' });
});

// adapters/site.js
export default ApplicationAdapter.extend({
  buildURL (modelName, id, snapshot, requestType, query) {
    let org = query.org;
    return `${ENV.APP.API_HOST}/api/v1/customers/${org}/sites/`;
  }
});

// routes/sites/index.js
export default Ember.Route.extend({
  model: function() {
    let superQuery = this._super(...arguments),
        org = superQuery.customer_orgCode;
    return this.store.query('site', {org:org});
  }
});

Upvotes: 4

Related Questions