具有自定义功能的 ember-data,可与非 JSONAPI 服务一起使用



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

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

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

获取/位置/: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')
});

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

假设您的模型类型是"位置"。 你会有一个这样的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);
    }
});

最新更新