2017-05-08 88 views
1

我試圖從我的REST API中使用燼來獲取品牌項目;但我的API響應與預期的燼數據不匹配。例如:在燼串行器上定義自定義根json節點

我的模型:

import DS from 'ember-data'; 

export default DS.Model.extend({ 
    name: DS.attr('string'), 
    isActive: DS.attr('boolean') 
}); 

我的API網址:http://localhost:3000/api/brands 與響應:

{"success":true, 
    "data":[ 
     {"id":1,"name":"Mine","isActive":true,"createdAt":"2017-04-23T20:36:49.000Z","updatedAt":"2017-04-23T20:44:32.000Z"}, 
     {"id":2,"name":"forever","isActive":true,"createdAt":"2017-04-23T20:41:14.000Z","updatedAt":"2017-04-23T20:43:57.000Z"} 
    ] 
} 

但是,灰燼期待一些這樣的:

"brands": [{ 

    "id": 1, 
    "name": "foo", 
    "isActive": "foo" 

}] 

我正在嘗試更改序列化器中名爲brand的根json節點。 JS,但我不能讓它工作。 :(

這裏我串行器/ brand.js

import DS from 'ember-data'; 

export default DS.RESTSerializer.extend({ 

}); 

和我的適配器/ application.js中

import DS from 'ember-data'; 
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin'; 
import config from '../config/environment'; 


export default DS.RESTAdapter.extend(DataAdapterMixin, { 
    host: `${config.host}`, 
    namespace: `${config.namespace}`, 
    authorizer: 'authorizer:custom' 
}); 

瀏覽器控制檯上顯示這樣的信息:

WARNING: Encountered "success" in payload, but no model was found for model name "success" (resolved model name using [email protected]:brand:.modelNameFromPayloadKey("success")) 
WARNING: Encountered "data" in payload, but no model was found for model name "datum" (resolved model name using [email protected]:brand:.modelNameFromPayloadKey("data")) 

哪有我說呃,在正確的數據是在哪裏?。有些幫助表示讚賞。

對不起,如果我的英文不好。

回答

1

正如您已經這樣做了,您可以覆蓋每個模型的RESTSerializer。

你想實現的是響應規範化。你可以在你的串行器(see the docs)覆蓋normalizeResponse正常化你的迴應:

import Ember from 'ember'; 
import DS from 'ember-data'; 

const { 
    RESTSerializer 
} = DS; 

const { 
    get 
} = Ember; 

export default RESTSerializer.extend({ 
    normalizeResponse(store, primaryModelClass, payload, id, requestType) { 
    // Only do normalization for reading: 
    if(requestType !== 'createRecord' && requestType !== 'updateRecord' && requestType !== 'deleteRecord') { 
     // Do your normalization here. For example (not tested): 
     payload = { 
     brands: get(payload, 'data') 
     }; 
    } 

    return this._super(store, primaryModelClass, payload, id, requestType); 
    } 
}); 

取而代之的首要normalizeResponse,你也可以覆蓋other normalization methods

+0

謝謝@Timm。它的工作:) –