Ember: how to add params from router to adapter - ember.js

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?

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});
}
});

Related

Recommended pattern to implement JSONAPI filter with query params in Ember?

I spent a chunk of time yesterday trying to include filter (reflecting the JSONAPI spec) in the query params of part of an Ember app. With Ember Data it is easy enough to pass a filter array to an endpoint, the problem I have is reflecting that filter array in the query params for a particular route. Note: other, non array, query params are working fine.
TL;DR I have tried various options without success and have a solution that really feels unsatisfactory and not at all DRY. I figure that many others must have tackled this problem and have surely found a better solution. Read on for details of what I have tried so far.
I started with something like this (I initially assumed it would work having read the Ember docs on query params):
Controller:
import Controller from '#ember/controller';
export default Controller.extend({
queryParams: ['sort', 'filter'],
sort: 'id',
init() {
this._super(...arguments);
this.set('filter', []);
},
});
Route:
import Route from '#ember/routing/route';
export default Route.extend({
queryParams: {
filter: {
refreshModel: true
},
sort: {
refreshModel: true
}
},
model(params) {
console.log(JSON.stringify(params)); // filter is always []
return this.get('store').query('contact', params);
}
});
Acceptance Test (this was just a proof of concept test before I started on the more complex stuff):
test('visiting /contacts with query params', async function(assert) {
assert.expect(1);
let done = assert.async();
server.createList('contact', 10);
server.get('/contacts', (schema, request) => {
let params = request.queryParams;
assert.deepEqual(
params,
{
sort: '-id',
"filter[firstname]": 'wibble'
},
'Query parameters are passed in as expected'
);
done();
return schema.contacts.all();
});
await visit('/contacts?filter[firstname]=wibble&sort=-id');
});
No matter how I tweaked the above code, params.filter was always [] in the Route model function.
I have searched around for best-practice on what would seem to be a common use case, but have not found anything recent. sarus' solution here from Nov 2015 works, but means that every possible filter key has to be hardcoded in the controller and route, which seems far from ideal to me. Just imagine doing that for 20 possible filter keys! Using sarus' solution, here is code that works for the above acceptance test but as I say imagine having to hardcode 20+ potential filter keys:
Controller:
import Controller from '#ember/controller';
export default Controller.extend({
queryParams: ['sort',
{ firstnameFilter: 'filter[firstname]' }
],
sort: 'id',
firstnameFilter: null,
init() {
this._super(...arguments);
}
});
Route:
import Route from '#ember/routing/route';
export default Route.extend({
queryParams: {
firstnameFilter: {
refreshModel: true
},
sort: {
refreshModel: true
}
},
model(params) {
if (params.firstnameFilter) {
params.filter = {};
params.filter['firstname'] = params.firstnameFilter;
delete params.firstnameFilter;
}
return this.get('store').query('contact', params);
}
});
I hope there's a better way!
If you don't have the requirement to support dynamic filter fields, #jelhan has provided a really good answer to this question already.
If you do need to support dynamic filter fields read on.
First of all, credit should go to #jelhan who put me on the right track by mentioning the possibility of serializing the application URL with JSON.stringify() and encodeURIComponent() together.
Here's example code with this working...
Controller:
import Controller from '#ember/controller';
export default Controller.extend({
queryParams: ['sort', {
filter: {
type: 'array'
}
}],
sort: 'id',
init() {
this._super(...arguments);
this.set('filter', []);
},
});
Route (no changes required):
import Route from '#ember/routing/route';
export default Route.extend({
queryParams: {
filter: {
refreshModel: true
},
sort: {
refreshModel: true
}
},
model(params) {
return this.get('store').query('contact', params);
}
});
Acceptance Test:
test('visiting /contacts with query params', async function(assert) {
assert.expect(1);
let done = assert.async();
server.createList('contact', 10);
server.get('/contacts', (schema, request) => {
let params = request.queryParams;
assert.deepEqual(
params,
{
sort: '-id',
"filter[firstname]": 'wibble',
"filter[lastname]": 'wobble'
},
'Query parameters are passed in as expected'
);
done();
return schema.contacts.all();
});
// The filter is represented by a Javascript object
let filter = {"firstname":"wibble", "lastname":"wobble"};
// The object is converted to a JSON string and then URI encoded and added to the application URL
await visit('/contacts?sort=-id&filter=' + encodeURIComponent(JSON.stringify(filter)));
});
Great! This test passes. The filter defined in the application URL is passed through to the Route. The Route's model hook makes a JSONAPI request with the filter correctly defined. Yay!
As you can see, there's nothing clever there. All we need to do is set the filter in the correct format in the application URL and the standard Ember Query Params setup will just work with dynamic filter fields.
But how can I update the filter query param via an action or link and see that reflected in the application URL and also make the correct JSONAPI request via the Route model hook. Turns out that's easy too:
Example Action (in controller):
changeFilter() {
let filter = {
firstname: 'Robert',
lastname: 'Jones',
category: 'gnome'
};
// Simply update the query param `filter`.
// Note: although filter is defined as an array, it needs to be set
// as a Javascript object to work
// this.set('filter', filter); - this seems to work but I guess I should use transitionToRoute
this.transitionToRoute('contacts', {queryParams: {filter: filter}});
}
For a link (say you want to apply a special filter), you'll need a controller property to hold the filter, we'll call it otherFilter and can then reference that in the link-to:
Example Controller property (defined in init):
init() {
this._super(...arguments);
this.set('filter', []);
this.set('otherFilter', {occupation:'Baker', category: 'elf'});
}
Example link-to:
{{#link-to 'contacts' (query-params filter=otherFilter)}}Change the filters{{/link-to}}
There you have it!
There is no reason to represent filter values in applications URL the same way as they must be for backend call to be JSON API complaint. Therefore I would not use that format for application URLs.
If you don't have the requirement to support dynamic filter fields, I would hard code all of them to have nice URLs like /contacts?firstname=wibble&sort=-id.
Your code would look like this, if you like to support filtering for firstname and lastname:
// Controller
import Controller from '#ember/controller';
export default Controller.extend({
queryParams: ['sort', 'page', 'firstname', 'lastname'],
sort: 'id',
});
// Route
import Route from '#ember/routing/route';
export default Route.extend({
queryParams: {
firstname: {
refreshModel: true
},
lastname: {
refreshModel: true
}
sort: {
refreshModel: true
}
},
model({ firstname, lastname, sort, page }) {
console.log(JSON.stringify(params)); // filter is always []
return this.get('store').query('contact', {
filter: {
firstname,
lastname
},
sort,
page
});
}
});
If you have to support dynamic filter fields, I would represent the filter object in application URL. For serialization you could use JSON.stringify() and encodeURIComponent() together. The URL would then look like /contacts?filter=%7B%22firstname%22%3A%22wibble%22%7D&sort=-id.

Why does my Ember computed property on hasMany relationship not update?

I have an Ember Data model as:
export default DS.Model.extend({
name: DS.attr('string'),
friends: DS.hasMany('friend',{async:true}),
requestedFriendIds: Ember.computed('friends',function(){
return this.get('friends').then(function(friends){
return friends.filterBy('status','Requested').mapBy('id');
});
})
});
I have a route setup that uses it:
export default Ember.Route.extend({
model: function(params){
return Ember.RSVP.hash({
memberProfile:this.store.find('member-profile', params.memberprofile_id).then(function(memberProfile)
{
return Ember.RSVP.hash({
requestedFriendIds:memberProfile.get('requestedFriendIds'),
UserId:memberProfile.get('user.id'),
Id:memberProfile.get('id')
});
}),
});
}
});
},
And htmlbars that utilize the route model. My computed property is always correctly called on a reload, but isn't refreshed on a user action 'Add Friend', which changes the store by adding a friend and the profile.friends' record like this:
actions:
{
addFriend:function(profile_id,)
{
this.store.findRecord('member-profile',memberProfile).then(function(member){
var friend = this.store.createRecord('friend',
{
member:member,
status:'Requested',
timestamp: new Date(),
});
friend.save();
member.get('friends').pushObject(friend);
member.save();
}.bind(this));
}
}
Some notes: I've tried the computed property on 'friends','friends.[]'. My code base is Ember 2.0.1, with Ember.Data 1.13.12, and as such 'friends.#each' is deprecated. The underlying data is correctly updated in the backing store (EmberFire). I've debugged into EmberData and I see that the property changed notifications invalidation code is called. This is only a selection of the code...
What am I missing...? Is there a better way to approach this?
I think you should watch friends.[] instead of only friends:
requestedFriendIds: Ember.computed('friends.[]',function(){
return this.get('friends').then(function(friends){
return friends.filterBy('status','Requested').mapBy('id');
});
})
And you could probably put your action in your route and manually refresh model (it might be issue with promise result not binding to changes in CP). So, in your route:
actions: {
addFriend(profile_id) {
this.store.findRecord('member-profile', memberProfile).then(member => {
let friend = this.store.createRecord('friend',
{
member:member,
status:'Requested',
timestamp: new Date()
});
friend.save();
member.get('friends').pushObject(friend);
member.save();
this.refresh();
});
}
}
The most important part is using this.refresh() in Ember.Route.

Ember data side loading with JSONAPI

The request generated for my route is http://api.myApp.com/tags/123/products, but I need to do some side loading to improve performance, the desired XHR would be:
http://api.myApp.com/tags/123/products?include=sideload1,sideload2,sideload3
My router looks like this:
this.route('tags', function() {
this.route('tag', { path: ':id' }, function() {
this.route('products', function() {
});
});
});
I'll like to sideload some async models for products, currently I have:
// app/routes/tags/tag/products.js
model() {
return this.modelFor('tags.tag').get('products');
}
How would I go about adding query params in route?
I'm doing something similar in a project and store.query(type, { query }); has worked for me. http://emberjs.com/blog/2015/06/18/ember-data-1-13-released.html#toc_query-and-queryrecord
Try doing a store.query when defining your model and passing in
{include: "sideload1,sideload2,sideload3"}
Another option could be creating an adapter for your model and using buildURL to add on the query params... However this is a bit hacky and shouldn't be necessary if your API is following the JSON API standards.
App.TagsAdapter = DS.JSONAPIAdapter.extend({
buildURL: function(type, id) {
var baseURL = 'http://api.myApp.com/tags/123/products';
var method = '?include=sideload1,sideload2,sideload3';
return baseURL + method;
}
});

Retrieve count (total) from non-default REST API

I would like to query my server for this URL http://localhost:1337/api/posts/count?category=technology using Ember. I'm using the default RESTAdapter like this:
export default DS.RESTAdapter.extend({
coalesceFindRequests: true,
namespace: 'api',
)};
The Post model looks like this:
import DS from 'ember-data';
var Post = DS.Model.extend({
title: DS.attr('string'),
permalink: DS.attr('string'),
body: DS.attr('string')
});
export default Post;
How do I make such a request?
I think you have at least two ways to achieve that when you don't have a control over your backend. Otherwise, you can still use the RESTful API (see the last section of my answer).
Override buildURL
The first one is to use the existing RESTAdapter functionalities and only override the buildURL method:
var PostAdapter = DS.RESTAdapter.extend({
namespace: 'api',
buildURL: function(type, id, record) {
var originalUrl = this._super(type, id, record);
if (this._isCount(type, id, record)) { // _isCount is your custom method
return originalUrl + '/count';
}
return originalUrl;
}
});
where in the _isCount method you decide (according to record property for example) if it's what you want. And then, you can pass the params using the store:
this.store.find('post', {
category: technology
});
Override findQuery
The second way is to override the whole findQuery method. You can either use the aforementioned DS.RESTAdapter or use just DS.Adapter. The code would look as the following:
var PostAdapter = DS.Adapter.extend({
namespace: 'api',
findQuery: function(store, type, query) {
// url be built smarter, I left it for readability
var url = '/api/posts/count';
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.getJSON(url, query).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null;
Ember.run(null, reject, jqXHR);
});
});
},
});
and you use the store as in the previous example as well:
this.store.find('post', {
category: technology
});
Obtaining 'count' from meta
If you have a complete control on your backend, you can leverage the power of metadata.
The server response then would be:
// GET /api/posts/:id
{
"post": {
"id": "my-id",
"title": "My title",
"permalink": "My permalink",
"body": "My body"
},
"meta": {
"total": 100
}
}
and then you can obtain all the meta information from:
this.store.metadataFor("post");
Similarly, you can use this approach when getting all the posts from /api/posts.
I hope it helps!

how to receive variables sent by transitionToRoute

I read at
http://emberjs.com/guides/controllers/
the following code:
I have a search box and want to send the value of the search box to the SearchController.
App.ApplicationController = Ember.Controller.extend({ // the initial
value of the `search` property search: '',
actions: {
query: function() {
// the current value of the text field
var query = this.get('search');
this.transitionToRoute('search', { query: query });
} } });
How can i get the query parameter in the SearchController and then show it in search.hbs?
I am working with ember- cli.
The router is
import Ember from 'ember';
var Router = Ember.Router.extend({
location: NENV.locationType
});
Router.map(function() {
this.route('search');
});
export default Router;
I set up a route under routes/search.js
export default Ember.Route.extend({
model : function (params) {
console.debug("hi");
return params;
},
setupController: function(controller,model) {
var query = model.query;
console.debug("query is");
console.debug(query);
}
});
When debugging i get an error:
ember More context objects were passed than there are dynamic segments
Thanks,
David
You need to define your search route to be dynamic, so if you change your route definition to something like this
Router.map(function() {
this.resource('search', {path: '/search/:query});
})
This should work as you are expecting. Let me know if anything.
Cheers!