如何在具有 ember-data 的路由器上获取 jsonapi 的包含值?

How to get included values of jsonapi on a router with ember-data?

我正在使用 jsonapi 指令在 ember.js 应用程序和 API 之间建立连接。我有一个 track 可能有 50 个或更多 comments,我需要将它们加载到路由上以执行一些逻辑。

这是 API 的示例响应:

{
   "data": {
       "id": 1,
       "type": "track",
       "attributes": {
           "name": "XPTO"
       },
       "relationships": {
           "comment": {
               "data": [
                   {"id": 1, "type": "comment"}
               ]
           }
       }
   },
   "include": [
       {
          "id": 1,
          "type": "comment",
          "attributes": {
             "text": "Lorem ipsum..."
          }
       }
   ]
}

现在想象一下有 50 条评论,每次调用都发出请求会非常耗时。如果我在带有 each 循环的视图中执行此操作,它不会发出所有请求,但我尝试在路由中访问它时,它会发出所有请求。我如何使用以下代码实现它?

this.store.findRecord('track', 1).then((t) => {
   // logic here
   // I tried this but it would make all the requests too
   t.get('comments');
})

你可以在你的适配器中使用 属性 "coalesceFindRequests"

coalesceFindRequests: true

如果您将 coalesceFindRequests 设置为 true,它将触发以下请求:

GET /comments?ids[]=1&ids[]=2

所以这只对所有评论进行一次调用。

Note: Requests coalescing rely on URL building strategy. So if you override buildURL in your app groupRecordsForFindMany more likely should be overridden as well in order for coalescing to work.