在Ember中使用自定义序列化器和来自Apigility的hal json

时间:2017-02-15 18:10:38

标签: ember.js apigility hal-json

因此,我正在构建我们网站的前端,长话短说,我们的API调用的位置是apigility。我对Ember来说还是一个新手,所以我一直在不断提供大量信息,以便最好地完成这项工作。 apigility设置为提供REST服务,但输出格式如下:

{
  _links: {
    self: {
      href: "http://localhost:8888/article?page=1"
    },
    first: {
       href: "http://localhost:8888/article"
    },
    last: {
      href: "http://localhost:8888/article?page=1"
    }
  },
  _embedded: {
    article: [
      {
        nid: 1,
        body_value: "Lorem Ipsum etc etc",
        created: 1487176722,
        _links: {
          self: {
            href: "http://localhost:8888/article/1"
          }
        }
      }
    ]
  },
  page_count: 1,
  page_size: 25,
  total_items: 1,
  page: 1
}

首先,因为我只想尝试一个概念验证,所以这就是我的序列化器:

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
    primaryKey: 'nid',
    normalizeResponse: function(store, primaryModelClass, payload, id, requestType) {   
        return {
            data: payload._embedded.article,                
        };
    }
});

我也在为我的apadpter使用RESTAdapter。

最后是我的article.js模型

import DS from 'ember-data';

export default DS.Model.extend({
    body_value: DS.attr('string'),
    nid: DS.attr('number')
});

它目前给我的错误是:

You must include an 'id' for undefined in an object passed to 'push'

从这个错误中我觉得它正确地得到了这篇文章'来自我的api调用的部分,但是primaryKey部分似乎没有生效。

如果我删除了序列化程序的内容,我会得到以下错误列表:

ember.debug.js:7062WARNING: Encountered "embedded" in payload, but no model was found for model name "embedded" (resolved model name using ember-drupal@serializer:application:.modelNameFromPayloadKey("embedded"))
ember.debug.js:7062WARNING: Encountered "page_count" in payload, but no model was found for model name "page-count" (resolved model name using ember-drupal@serializer:application:.modelNameFromPayloadKey("page_count"))
ember.debug.js:7062WARNING: Encountered "page_size" in payload, but no model was found for model name "page-size" (resolved model name using ember-drupal@serializer:application:.modelNameFromPayloadKey("page_size"))
ember.debug.js:7062WARNING: Encountered "total_items" in payload, but no model was found for model name "total-item" (resolved model name using ember-drupal@serializer:application:.modelNameFromPayloadKey("total_items"))
ember.debug.js:7062WARNING: Encountered "page" in payload, but no model was found for model name "page" (resolved model name using ember-drupal@serializer:application:.modelNameFromPayloadKey("page"))

如果我需要包含任何其他信息/代码,请告诉我。

修改

注意:API开发人员确实从

有时你只需要从一个干净的石板开始,是吗?

这就是我的序列化程序的样子,它按预期工作:

export default DS.RESTSerializer.extend({
    normalizeResponse(store, primaryModelClass, payload, id, requestType) {
        payload = { article: payload._embedded[primaryModelClass.modelName] };
        return this._super(store, primaryModelClass, payload, id, requestType);
    },
});

0 个答案:

没有答案