2017-03-27 64 views
0

我正在處理一個數據模型,它具有一組將始終存在的預定義屬性以及用戶爲其定義的其他自定義屬性。動態地定義屬性到Ember數據模型

一家公司有很多角色。除了所有角色在不同公司使用的固定屬性集之外,使用此係統的每個公司都希望爲其所有角色定義自定義屬性。

的想法將是JSON的API,然後角色有效載荷與所有的屬性,習慣或不:

{ 
    "id": "123", 
    "type": "roles", 
    "attributes": { 
    "name": "CEO", 
    "salary": 100000, 
    "favoriteColor": "blue" 
    } 
} 

在上面的作用,namesalary是默認屬性,存在於所有的角色不管公司,但favoriteColor是一個自定義屬性,特定公司擁有這個角色定義爲他們需要具備的所有角色。 ,

我想知道如果我能擺脫這樣的使用灰燼給出的數據,我不能確定這些自定義的角色模型定義屬性:

// app/models/role.js 
export default DS.Model.extend({ 
    name: DS.attr('string'), 
    salary: DS.attr('number'), 
}) 

爲了使問題更糟糕的是,這個想法是這些自定義屬性不一定是字符串值,但它們也可以指定它們的類型。因此,一家公司可能需要favoriteColor類型string,以及birthDate類型date

回答

1

我想補充一個屬性(您的服務器將需要返回附加參數在config屬性):

// app/models/role.js 
export default DS.Model.extend({ 
    name: DS.attr('string'), 
    salary: DS.attr('number'), 
    config: DS.attr() // accepts anything, including json 
}) 

選項1:處理序列化到由屬性您normalize您自定義序列化器的功能,將config中的值推送到序列化屬性中。事情是這樣的:

// serializers/role.js 
export default <Your Base Serializer>.extend({ 
     normalize(typeClass, hash) { 
      const result = this._super(typeClass, hash); 

      result.data.attributes = Object.keys(data.attributes.config).reduce((acc, value) => { 
       acc[value] = result.data.attributes.config[value]; 
       return acc 
      }, result.data.attributes); 

      return result; 
     }, 
    }); 

選項2(如果你的選擇是有限的):使用計算功能alias

// app/models/role.js 
export default DS.Model.extend({ 
    name: DS.attr('string'), 
    salary: DS.attr('number'), 
    config: DS.attr(), // accepts anything, including json 

    favoriteColor: Ember.computed.alias('config.favoriteColor') 
}) 
0

使用定製jsona數據格式,它可能是創造燼非常有幫助數據模型自動。此外,還可以自動從您的餘燼數據模型創建正確的JSON :)