如何使用 Backbone 读取通过同一 REST URL 返回的两个不同对象

How to read two different objects returned via the same REST URL using Backbone?

本文关键字:对象 两个 返回 URL 读取 Backbone 何使用 REST      更新时间:2023-09-26

我有一个 REST URL,比如

/users/<user_id>/entities

其中返回 2 个对象:

{
    "players":
    {
       "test_player2":
       {
           "_id": "test_player2",
           "user": "f07590567f3d3570b4f35b4fd79f18b3"
       },
       "test_playerX":
       {
           "_id": "test_player2",
           "user": "f07590567f3d3570b4f35b4fd79f18b3"
       }
    },
    "games":
    {
      "game1" :{},
      "game2" :{},
    }
}

如何设计主干对象以使用此数据?

要求:我想要两个不同的主干对象:玩家和游戏,它们应该通过相同的 url(如上所述)填充。

PS:设计这种 REST URL 甚至是一种正确的做法吗?

设计这种 REST URL 甚至是一种正确的做法吗?

不,这不是正确的做法。在 REST 中,单个 URL 应该表示单个资源。因此,您的/users/<user_id>/entities URL 应/users/<user_id>/players且仅返回玩家列表,/users/<user_id>/games且仅返回游戏列表。

但是,有时可能无法控制 API 返回的内容。通常,嵌套对象就是这种情况(您可以使用现有对象来执行此操作,但理想情况下,您需要更改 API):

{
    "players":
    {
        "id": 1,
        "games":
        {
           "id": 1745,
           "title": "Team Fortress 2"
        }
    }
}

在这种情况下,您将使用模型的parse函数,如下所示:

parse: function(response)
{
    // Make sure "games" actually exists and is an array to make a collection from
    if(_.isArray(response.games))
    {
        // Backbone will automatically make a collection of models from an array
        // Use {parse: true} if you want the receiving collection to parse as if a fetch had been done
        this.games = new GamesCollection(response.games,{parse: true});
    }
}

通过覆盖parse并使用{parse:true},您可以几乎无限期地构建模型。这样做不一定是理想的(这个想法是每个集合负责自己的模型),但它适用于获取复合对象并且无法更改 API 返回的内容的情况。