多态关系ember数据url端点调用混乱

时间:2016-02-02 07:14:57

标签: ember.js

您好我正在尝试建立多态关系 用户有一个可以是admin的配置文件,point_of_contact。

在下面提到的sessionAccount服务中 在致电user.get('profile')时,我的理解是ember会巧妙地致电/pointOfContacts/1,但它正在呼叫/profiles/1

//串行器/ application.js中

import { ActiveModelSerializer } from 'active-model-adapter';
export default ActiveModelSerializer.extend();

//适配器/ 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})
});

//模型/ 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'),
});

由于ember cli mirage尚不支持多态关系。 我的海市蜃楼配置看起来像这样

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

所以我的json对user /:id的响应看起来像这样

{
  "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"
  }]
}

现在我想将此角色放入名为sessionAccount的服务中。这样我就可以在应用程序的任何地方使用它 我正在使用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');
      });
    }
  })
});

0 个答案:

没有答案