使用带有自定义序列化程序的ember-data

时间:2015-05-18 02:33:19

标签: javascript ember.js ember-data ember-cli

我可以说一个非标准的json api。我试图使用ember-data,所以从我的阅读中我需要创建一个序列化器。我试图在网上找到解释如何做到这一点的文章,但没有找到任何有用的东西。我试着通过余烬指南查看,但也没有发现任何东西。这是我的api的一个例子:

数据收集:

{
  "data": [
    {
      "id": 14,
      "name": "company name",
      "slug": "company-name",
      "detail": {
        "data": {
          "id": 10,
          "address": "10000 sw 16th ct",
          "city": "Hollywood",
          "state": "Alabama"
        }
      },
      "employees": {
        "data": [
          {
            "id": 17,
            "first_name": "Peter",
            "last_name": "Griffin",
            "email": "company-name@Griffin.co"
          },
          {
            "id": 18,
            "first_name": "Robert",
            "last_name": "Gornitz",
            "email": null
          }
        ]
      }
    },
    {
      "id": 8,
      "name": "company name",
      "slug": "company-name",
      "detail": {
        "data": {
          "id": 8,
          "address": "1000 n university dr",
          "city": "Fort Lauderdale",
          "state": "West Virginia"
        }
      },
      "employees": {
        "data": [
          {
            "id": 15,
            "first_name": "Peter",
            "last_name": "Griffin"
          },
          {
            "id": 16,
            "first_name": "Peter",
            "last_name": "Griffin"
          }
        ]
      }
    }
  ]
}

以下是与其关系的项目:

{
  "data": {
    "id": 1,
    "name": "company name",
    "slug": "company-name",
    "detail": {
      "data": {
        "id": 1,
        "address": "1515 n university dr",
        "city": "Miami",
        "state": "Mississippi"
      }
    },
    "employees": {
      "data": [
        {
          "id": 1,
          "first_name": "Peter",
          "last_name": "Griffin",
          "email": "peter@email.com"
        },
        {
          "id": 2,
          "first_name": "Peter",
          "last_name": "Griffin",
          "email": "peter@email.com"
        }
      ]
    }
  }
}

是否有任何好的资源告诉我如何做到这一点?或者我应该不使用ember-data?

1 个答案:

答案 0 :(得分:2)

使用Ember Data从我身边得到一些提示。我相信你要么必须能够适应api,要么写一个反序列化器:

<强> 1。根密钥&#34;数据&#34;

Ember期望根密钥是模型的名称(例如&#34;公司&#34;)。您可以通过创建应用程序序列化程序并通过从“数据”中获取有效负载来覆盖extractArray和extractSingle方法,从而轻松解决这个问题。键而不是模型&#34; typeKey&#34;。

<强> 2。嵌入式记录

您可以使用EmbeddedRecordsMixin。但为此你必须跳过根键&#34;数据&#34;在嵌入式记录中并直接包含它们(例如&#34;员工&#34;:[{id:&#34; 2&#34;,...},...])

我要看一下EmbeddedRecordsMixin: http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize

希望有所帮助。