ember js get relationships of relationships - ember.js

My routes have something like this
return this.store.query('author', {filter:{username : username},
include: 'books, books.readers'})
as we can see author has Many-2-Many relationships with books, book have relationship with reader
How can I include books.reader when run query with author?

Ember Data provides the ability to query for records that meet certain criteria. Calling store.query() will make a GET request with the passed object serialized as query params. This method returns a DS.PromiseArray in the same way as findAll.
So for example in your case author with :username can be changed to the following code:
// GET to /persons?filter[username]=username
this.get('store').query('author', {
filter: {
username: username
}
}).then(function(username) {
// Do something with `username` which can be another filter and whatever else you want, give it a try.
});
Hope it can solve your problem.

Related

Nest.js serializer like Django

I am currently using Nest.js, Postgresql, Typeorm for my backend. Now I am trying to do is to see an specific entity field differently by each user.
For example there are 10 posts and one user has bookmarked 3 of them. Only a user who bookmarked the post can get isBookmarked = true, others isBookmarked = false.
I used Django a bit and I used serializer to implement the same logic. I looked for Nest.js serializer (https://docs.nestjs.com/techniques/serialization) but I think it is a bit different than what I thought. Please tell me how to use this serializer as Django does, or any other ways to implement the logic.
Since NestJS is using class-transform you can follow the documentation to achieve what you wants => https://github.com/typestack/class-transformer#additional-data-transformation
import { Transform } from 'class-transformer';
export class Post {
id: number;
#Transform(({ value }) => isBookmarkedByTheUser())
bookmarked: boolean;
}
Something like that ;)

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.
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

Find the class name of a relation from the instance of a model in ember JS

I have foo an instance of the ember-data model thing. thing.js has the following property :
owner: DS.belongsTo('user')
If I have foo with an empty owner, how can I, with only foo and the 'owner' string, retrieve the value 'user' representing the model of the owner relation?
EDIT: I want to allow my select-relation component to works with relations where the name is different from the class name
It sounds like you have some work to do to finish setting up your relationships. Have a read through this page of the guides.
If the relationships are set up correctly, to get the associated user, you should be able to do foo.owner. This assumes that users are already present in the store. I recommend using the Ember Inspector browser plugin to debug the relationships.
This looks like a use case for typeForRelationship.
In your example you should be able to do something like
store.modelFor('thing').typeForRelationship('owner', store);
If you don't like that approach you can use the belongsTo reference API, where you use the meta data from the relationship to get the type
foo.belongsTo('owner').type
The only thing with that approach is that the type property may not be public API and possible (though unlikely) to change at some point.
It seems I can do the following :
this.get('model').get('_internalModel._relationships.initializedRelationships.'+this.get('relation')+'.relationshipMeta.type')
model being an instance and relation the string of the relation name, it correctly return the model of the relation.
EDIT : a better solution not using private API courtesy from the ember discord :
function getRelatedModelName(record, relationName){
let ParentModelClass = record.constructor;
let meta = get(ParentModelClass, 'relationshipsByName').get(relationName);
return meta.type;
}

Ember distinguish record which is requested from server with params and without params

I'm trying to get two records from the server without knowing the ID's. The first record is requested without params and the second record with params.
It looks something like this:
model: function(){
return Ember.RSVP.hash({
cars: this.store.find('cars').then(function(car){
return car.get('firstObject');
}),
carsWithRange: this.store.find('cars', {date_from: momentLast30Days}).then(function(car){
return car.get('firstObject');
})
});
}
At the moment 'cars' and 'carsWithRange' sometimes returns the same record. I think this is happening because I use car.get('firstObject') from the cars models. Somehow I need to know that 'carsWithRange' is requested with the param 'date_from'.
Does anyone know how to fix this?
FYI I use Ember 1.12.1 with Ember Data 1.0.0-beta.15
We finally solved it in the frontend by using this.store.findQuery (with a query which doesn't make a lot of sense) instead of this.store.find. This returns the exact record which is given by the server. But yeah it feels a bit hacky.

Custom Model URL

Is there currently (in the latest builds) a way of specifying a URL on a model-by-model basis? in Ember Data 1.0 beta? I have found some questions on SO and issues on Github around this, but most are out-dated.
For example, I have a model that's called App.PaymentSearchResult and rather than having the request go to /payment_search_results I would like it to go to /payments/search. Where would I override the URL used for a given model (rather than overriding buildURL on the RESTAdapter)?
You can override the the find adapter
but it's kind of hackish, i think however i would take another approach. Idealy you want your Ember models to reflect your backend's models, so why would you need a PaymentSearchResult? When you probably already have a Payment model?
If you need to search in your payment records, why not handle it using query params?
http://emberjs.com/guides/models/finding-records/#toc_querying-for-records
this.store.find('payment', { total: "22" });
Then you want to answer accordingly on the server.
If you want to do a search which returns multiple models, you do this with a manual ajax request.
var self = this;
$.get( "/search", { name: "John", time: "2pm" }, function(result) {
self.store.pushMany(result);
});
PushMany assumes a sane JSON structure.
http://emberjs.com/api/data/classes/DS.Store.html#method_pushMany