将后端的响应序列化到 store ember store

Serialize the response from backend to store ember store

我的后端回复不是 ember 存储的格式。我无法序列化响应。

response.json

[{
    "pk": 127,
    "url": "http://example.com/api/galleries/127/",
    "gallery_name": "Faces",
    "thumbnail_url": "https://example.cloud.net/galleryThumbs/2656a05c-4ec7-3eea-8c5e-d8019454d443.jpg",
    "time": "1 month ago",
    "description": "Created by user",
    "is_following": true,
    "feedPhotos": [{
            "pk": 624,
            "url": "http://example.com/api/photos/624/",
            "profilePic": "https://example.cloud.net/userDPs/50906ce2-394d-39c8-9261-8cf78e3611c2.jpg",
            "userName": "Nabeela",
            "userKarma": 915,
            "caption": "Old woman spinning her 'chhos-khor' ...a rotation of which is equivalent to the recitation of a mantra.",
            "numComments": 0,
            "owner": "http://example.com/api/users/44/",
            "time": "1 month ago",
            "photo_url": "https://example.cloud.net/photos/9cbd6423-3bc5-36e0-b8b4-d725efb3249a.jpg",
            "comments_url": "http://example.com/api/photos/624/comments/",
            "numFives": 4,
            "fivers_url": "http://example.com/api/photogalleries/1362/fivers/",
            "fivers_pk": 1362,
            "fullphoto_url": "http://example.com/api/photogalleries/1362/photo/",
            "fullphoto_pk": 1362,
            "is_fived": true,
            "hiFiveKarma": 1,
            "owner_pk": 44,
            "userFirstName": "Nabeela",
            "is_bookmarked": false
        }, {
            "pk": 574,
            "url": "http://example.com/api/photos/574/",
            "profilePic": "https://example.cloud.net/userDPs/b6f69e4e-980d-3cc3-8b3e-3eb1a7f21350.jpg",
            "userName": "Rohini",
            "userKarma": 194,
            "caption": "Life @ Myanmar!",
            "numComments": 0,
            "owner": "http://example.com/api/users/45/",
            "time": "2 months ago",
            "photo_url": "https://example.cloud.net/photos/eeae72d5-d6af-391e-a218-b442c0c7e34e.jpg",
            "comments_url": "http://example.com/api/photos/574/comments/",
            "numFives": 2,
            "fivers_url": "http://example.com/api/photogalleries/1303/fivers/",
            "fivers_pk": 1303,
            "fullphoto_url": "http://example.com/api/photogalleries/1303/photo/",
            "fullphoto_pk": 1303,
            "is_fived": false,
            "hiFiveKarma": 0,
            "owner_pk": 45,
            "userFirstName": "Rohini",
            "is_bookmarked": false
        }
    ]
}, {
    "pk": 65,
    "url": "http://example.com/api/galleries/65/",
    "gallery_name": "Royal",
    "thumbnail_url": "https://example.cloud.net/galleryThumbs/d8a900af-1f1d-3977-8cc8-b8bb36e32be5.jpg",
    "time": "2 months ago",
    "description": "This is a gallery about Royal",
    "is_following": false,
    "feedPhotos": [{
        "pk": 347,
        "url": "http://example.com/api/photos/347/",
        "profilePic": "https://example.cloud.net/userDPs/50906ce2-394d-39c8-9261-8cf78e3611c2.jpg",
        "userName": "Nabeela",
        "userKarma": 915,
        "caption": "I cannot forget the name of this palace - Moti Mahal (translation: Pearl Palace). Indescribably beautiful, ainnit! at Mehrangarh fort, Jodhp",
        "numComments": 0,
        "owner": "http://example.com/api/users/44/",
        "time": "2 months ago",
        "photo_url": "https://example.cloud.net/photos/958ed406-708e-3f01-a2f4-9467cd709fdd.jpg",
        "comments_url": "http://example.com/api/photos/347/comments/",
        "numFives": 4,
        "fivers_url": "http://example.com/api/photogalleries/759/fivers/",
        "fivers_pk": 759,
        "fullphoto_url": "http://example.com/api/photogalleries/759/photo/",
        "fullphoto_pk": 759,
        "is_fived": false,
        "hiFiveKarma": 0,
        "owner_pk": 44,
        "userFirstName": "Nabeela",
        "is_bookmarked": false
    }, {
        "pk": 593,
        "url": "http://example.com/api/photos/593/",
        "profilePic": "https://example.cloud.net/userDPs/95ac6974-f7df-338c-ab84-99fa1df7514c.jpg",
        "userName": "Vikanshu",
        "userKarma": 932,
        "caption": "Marvelous architecture!! in Florence, Italy",
        "numComments": 0,
        "owner": "http://example.com/api/users/48/",
        "time": "1 month ago",
        "photo_url": "https://example.cloud.net/photos/7a86eb37-6c68-3d6c-b6cf-2e3b74d330dd.jpg",
        "comments_url": "http://example.com/api/photos/593/comments/",
        "numFives": 4,
        "fivers_url": "http://example.com/api/photogalleries/1363/fivers/",
        "fivers_pk": 1363,
        "fullphoto_url": "http://example.com/api/photogalleries/1363/photo/",
        "fullphoto_pk": 1363,
        "is_fived": false,
        "hiFiveKarma": 0,
        "owner_pk": 48,
        "userFirstName": "Vikanshu",
        "is_bookmarked": false
    }]
}]

如何使用 JSONPISerailizer 或 ember-cli 中的任何其他序列化程序对其进行序列化,以便将其存储在 ember store

Reference jsonapi.org ++++顶级: 根: JSON object 必须是每个 JSON API 请求响应的根。 一份文件必须至少包含一个 top-level members: 1.数据:文档"primary data" 2. errors: 错误数组 objects (id,status,code,title....) 3. meta: 包含 non-standard meta-information (copyright,author...)

的 meta object

member数据和错误不能co-exist在一起。 "data"{}

++++++资源 Objects 1. 资源 object 必须至少包含以下 top-level member *ID *类型

```
//structure-1
//for galleries
{
  "data": {
    "type": "galleries",
    "id": "1"
  }
}

//for photos
{
  "data": {
    "type": "photos",
    "id": "1"
  }
}
```
  1. 此外,资源 object 可能包含任何这些 top-level members *属性 *关系 *link秒 *元

//先添加属性

```
//structure-2
//for galleries
{
  "data": {
    "type": "galleries",
    "id": "1",
    "attributes": {
      "galleryName": "Faces"
      "thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
      "description": "Created by user",
    }
  }
}

//for photos
{
  "data": {
    "type": "photos",
    "id": "1",
    "attributes":{
       userName: "Nabeela",
       userKarma: 915
     }
  }
}
```

//添加关系 关系 object 必须至少包含以下其中一项 *links(包含至少一个 "self" 或 "related" 资源 link *数据 *元

//link in relationship (minimum one required from link,data,meta).
//
```
//structure-3
//for galleries
{
  "data":[{  //Array(square bracket as adding relationship one more item to data
    "type": "galleries",
    "id": "1",
    "attributes": {
      "galleryName": "Faces"
      "thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
      "description": "Created by user",
    },
    "relationships":{
       "links":{
      "self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
    },
    }]
  }
}
```

//关系中的数据

```
//structure-4
//for galleries
{
  "data": [{
    "type": "galleries",
    "id": "1",
    "attributes": {
      "galleryName": "Faces"
      "thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
      "description": "Created by user",
    },
    "relationships":{ //This has all your photo stuff
       "links":{
      "self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
    },
    "data": {       //picked it up from structure-1
          "type": "photos",
          "id": "77"
    }
    }]
  }
}
```

//添加相关资源"included"

``` //画廊

{
  "data": [{
    "type": "galleries",
    "id": "1",
    "attributes": {
      "galleryName": "Faces"
      "thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
      "description": "Created by user",
    },
    "relationships":{ //This has all your photo stuff
       "links":{
      "self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
    },
    "data": {       //picked it up from structure-1
          "type": "photos",
          "id": "77"
    }
    }],
    "included":[{
        "type": "photos",
        "id": "77",
        "attributes":{
            userName: "Nabeela",
            userKarma: 915
        },
    {
        "type": "photos",
        "id": "78",
        "attributes":{
            userName: "Nabeela",
            userKarma: 915
        }
   }]

  }
}

```

collection 秒。我没有信心,但试试这个

现在 collection 个画廊。

//画廊

{
  "data": [{
    "type": "galleries",
    "id": "1",
    "attributes": {
      "galleryName": "Faces"
      "thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
      "description": "Created by user",
    },
    "relationships":{ //This has all your photo stuff
       "links":{
      "self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
    },
    "data": {       //picked it up from structure-1
          "type": "photos",
          "id": "77"
    }
    },{
    "type": "galleries",
    "id": "2",
    "attributes": {
      "galleryName": "Faces"
      "thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
      "description": "Created by user",
    },
    "relationships":{ //This has all your photo stuff
       "links":{
      "self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
    },
    "data": {       //picked it up from structure-1
          "type": "photos",
          "id": "79"
    }
    }],
    "included":[{
        "type": "photos",
        "id": "77",
        "attributes":{
            userName: "Nabeela",
            userKarma: 915
        },{
        "type": "photos",
        "id": "78",
        "attributes":{
            userName: "Nabeela",
            userKarma: 915
        },{
        "type": "photos",
        "id": "79",
        "attributes":{
            userName: "Nabeela",
            userKarma: 915
        }
   }]

  }
}

============实现部分=============================== ==

JSON序列化程序规范化过程遵循以下步骤

*normalizeResponse : 入口方法。 *normalizeCreateRecordResponse :用于特定操作的 normalizeResponse。 *normalizeSingleResponse|normalizeArrayResponse: - 对于像 createRecord 这样的方法。我们期待一个单一的记录回来。 - 对于像 findAll 这样的方法,我们期望返回多条记录。

+归一化= normalizeArray 迭代并为它的每条记录调用 normalize normalizeSingle 调用一次。

+提取ID |提取属性 |提取关系 = 将这些方法的委托规范化以将记录负载转换为 jsonAPI 格式

从 normalizeResponse 方法开始。如果您打开并看到 normalizeResponse 方法

在json-serializer link 标准化响应:https://github.com/emberjs/data/blob/v2.2.1/packages/ember-

data/lib/serializers/json-serializer.js#L192

你找到了一个开关盒 switch(requestType)。如果请求类型如果 "findRecord" 然后调用 "normalizeFindRecordResponse" "queryRecord" 然后调用 "normalizeQueryRecordResponse" "findAll" 然后调用 "normalizeFindAllResponse" ...等等等等。 如果您注意到传递给所有方法的参数与规范化的参数相同

(...参数):)

**让我们开始findAll 即 normalizeResponse -> normalizeFindAllResponse -> normalizeArrayResponse 因为 normalizeFindAllResponse 方法只有一行调用

normalizeArrayResponse。

normalizeFindAllResponse

normalizeResponse -> normalizeFindAllResponse -> normalizeArrayResponse ->

_normalizeResponse{ extractMeta,normalize }

extractMeta [提取分页等元信息] 如果单身:归一化 []

emberjs 文档中规范化方法的示例

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

export default DS.JSONSerializer.extend({
  normalize: function(typeClass, hash) {
    var fields = Ember.get(typeClass, 'fields');
    fields.forEach(function(field) {
      var payloadField = Ember.String.underscore(field);
      if (field === payloadField) { return; }

      hash[field] = hash[payloadField];
      delete hash[payloadField];
    });
    return this._super.apply(this, arguments);
  }
});
```

"normalizeArrayResponse 调用`return this._normalizeResponse

(商店、primaryModelClass、有效载荷、id、requestType、false)。 所以 isSingle 对于 _normalizeResponse 方法是假的。所以我们将不得不推动所有

包含数组的相关记录 在我们的例子中,照片是由“_normalizeRespose”中的以下片段完成的

方法。 _normalizeResponse

```
else{
  documentHash.data = payload.map((item) => {
    let { data, included } = this.normalize(primaryModelClass,item);
    if(included){
      documentHash.included.push(...included);
    }
    return data;
  });

  return documentHash;
}
```

在我们的 JSON 服务器响应的上下文中,事情仍然不清楚 但至少我们现在知道流程了。

让我们尝试将它应用于 findAll(按照上面的流程)。

  1. 运行 "ember g serializer application" //假设您正在使用 ember-cli 并且您

打算使此序列化器对应用程序通用。

截至目前,我不知道如何以及何时调用 normalizeResponse。 :( 我刚刚扫描并猜测从商店调用的服务器接收数据

normalizeResponseHelpers 依次调用 normalizeResponse。

在任何情况下 "normalizeResponse" 将发送有效负载和其他必要的

normalizeFindAllResponse(...arguments) 的信息,后者将调用

normalizeArrayResponse(...arguments) 依次调用“_normalizeRespone”。

这是我们需要采取行动的地方 对于 extraMeta 和规范化。 +extraMeta 我不确定您 json 回复中是否有任何元信息。 如果有可以参考docs

中提到的例子

extractMeta

所以我想您可以在您的应用程序中直接使用示例中的规范化方法 ;)。

请尝试检查。由于我自己正在学习 ember,所以我不能保证它会起作用,但它应该会起作用。 lonngggg 解释是我在学习 problem/solution

时的想法
//app/serializers/application.js

+normalize
```
import DS from 'ember-data';

export default DS.JSONSerializer.extend({
  normalize: function(typeClass, hash) {
    var fields = Ember.get(typeClass, 'fields');
    fields.forEach(function(field) {
      var payloadField = Ember.String.underscore(field);
      if (field === payloadField) { return; }

      hash[field] = hash[payloadField];
      delete hash[payloadField];
    });
    return this._super.apply(this, arguments);
  }
});
```

服务器 JSON 中的主键是 pk。你也得提一下

http://emberjs.com/api/data/classes/DS.JSONSerializer.html#property_primaryKey app/serializers/application.js

import DS from 'ember-data';

export default DS.JSONSerializer.extend({
  primaryKey: 'pk'
});