具有自定义功能的ember-data,用于非JSONAPI服务

时间:2016-05-26 21:53:12

标签: ember.js ember-data

我有点困惑,只需要一些清晰度: 我应该实现自定义适配器还是自定义序列化器?

我需要我的ember应用程序与REST / json后端通信。

我希望我的ember应用程序将资源公开为:

  

GET / locations /:id

但它连接的主机的资源位于:

  

获取http://server/api/location/:id

来自服务器的有效负载:

{
  "id": "7ff3269e-d16c-4cc4-954d-aef8e662e0f6",
  "geo": {
    "latitude": 0,
    "longitude": 0
  },
  "typedAddress": {
    "addressType": "US",
    "countryCode": "US",
    "name": "string",
    "address1": "string",
    "address2": "string",
    "address3": "string",
    "postalCode": "string"
  },
  "customDescription": "string",
  "timezone": "string"
}

我的模型用于此:

export default Model.extend({
  latitude: attr('number'),
  longitude: attr('number'),
  addressType: attr('string'),
  countryCode: attr('string'),
  address1: attr('string'),
  address2: attr('string'),
  address2: attr('string'),
  city: attr('string'),
  state: attr('string'),
  briefPostalCode: attr('string'),
  postalCode: attr('string'),
  timezone: attr('string')
});

1 个答案:

答案 0 :(得分:4)

您只需使用RESTAdapter并编写自己的Serializer

假设您的模型类型为“location”。你会有app/serializers/location.js这样的:

export default DS.RESTSerializer.extend({
    normalizeResponse(store, primaryModelClass, payload, id, requestType) {
        let data= {
            locations: [{
                id: payload.id,
                latitude: payload.geo.latitude,
                // etc. for all your properties
            }]
        };
        return this._super(store, primaryModelClass, data, id, requestType);
    }
});