Hi I am trying to set up polymorphic relationship user has one profile which can be admin, point_of_contact.
In the sessionAccount service mentioned below on calling user.get('profile')
my understanding is ember will smartly call /pointOfContacts/1
but it is calling /profiles/1
//serializers/application.js
import { ActiveModelSerializer } from 'active-model-adapter';
export default ActiveModelSerializer.extend();
//adapters/application.js
import ActiveModelAdapter from 'active-model-adapter';
export default ActiveModelAdapter.extend();
//model.user.js
import DS from 'ember-data';
const {
attr,
belongsTo
}=DS;
export default DS.Model.extend({
email: attr('string'),
profile: belongsTo('profile',{polymorphic:true , async: true})
});
//model/profile.js
import DS from 'ember-data';
export default DS.Model.extend({
});
//model pointOfContact
import DS from 'ember-data';
import Profile from './profile';
const {
attr,
} = DS;
export default Profile.extend({
firstName: attr('string'),
});
Since ember cli mirage does not support polymorphic relationships yet. my mirage config looks like this
this.get('/users/:id',(schema,request)=>{
let record = schema.db.users.find(request.params.id);
let { id, email, token , profileId, profileType } = record;
let profileTypeModel = pluralize(profileType);
let profileRecord = schema.db[profileTypeModel].find(profileId);
let userRecord = { id:id,
email:email,
token:token,
profile_id: profileId,
profile_type: profileType
};
let formattedResponse = { user: userRecord };
formattedResponse[profileTypeModel] = [profileRecord];
return formattedResponse;
});
so My json response to user/:id looks like this
{
"user": {
"id": "1",
"email": "some@email.com",
"profile_id": 1, // these two lines
"profile_type": "pointOfContact" // tell Ember Data what the polymorphic
// relationship is.
},
"pointOfContacts": [{
"id": 1,
"firstName": "somefirstname"
}]
}
Now I want to put this role into a sevice called sessionAccount. So that i can use it anywhere in application I am using ember-simple-auth
import Ember from 'ember';
const {
inject:{
service
},
computed
} = Ember;
export default Ember.Service.extend({
session: service(),
store: service(),
account: computed('session.data.authenticated.user.id',function(){
const userId = this.get('session.data.authenticated.user.id');
if(!Ember.isEmpty(userId)){
return this.get('store').findRecord('user',userId).then((user)=>{
return user.get('profile');
});
}
})
});
Aucun commentaire:
Enregistrer un commentaire