How can I add query params to a JSON:API hasMany request?


#1

Here’s my simple model. My API returns JSON:API responses including links properties so that Ember Data knows where to fetch relationship data.

models/structure.js:

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  properties: DS.hasMany('property'),
});

Say I’ve already fetched an Ember Data structure object and I want to fetch it’s properties:

structure.get('properties')

Great! Ember Data uses this structure’s links data to build the URL to fetch only the properties for this particular structure. But now I want to add a query param to filter the data server side to get only properties of a certain type: eg. ?filter[type]=string. Normally to add query params I can do a manual query like:

this.store.query('property', {
  filter: {
    type: 'string'
  }
})

But this is loading all properties and I want to load just the properties for the structure. With nested relationship routes such as /api/structures/:structure_id/properties just adding a structure_id: ID param to the this.store.query( call won’t work because it will use the wrong API endpoint: /api/properties.

This seems like a pretty basic requirement for any JSON:API implementation? Is there no officially supported way to do this short of using this unmaintained addon: https://github.com/mdehoog/ember-data-has-many-query


#2

So the add-on doesn’t work for you?

Alternatively, what you can do is override findHasMany in your adapter to include the query params in the request to the API. I wrote about it here: https://emberigniter.com/adding-query-parameters-hasmany-relationship/