从 ember 数据查询访问“链接”属性

Accessing the `links` property from a ember data query

当使用 JSONAPIAdaper 时,我在商店中查询模型,服务器响应包括 json-api spec 指定的 "links" 属性,响应如下.

{
  "links": {
    "self": "http://localhost:4200/api/v0/blog-posts?size=10",
    "first": "http://localhost:4200/api/v0/blog-posts?size=10&page=0",
    "last": "http://localhost:4200/api/v0/blog-posts?size=10&page=1",
    "next": "http://localhost:4200/api/v0/blog-posts?size=10&page=1"
  },
  "data": [{
    "id": 1,
    "type": "blog.posts",
    "attributes": {
      "published": "2015-04-04T00:56:36.768Z"
    },
    "relationships": {
      "revisions": {
        "data": [
          { "id": 1, "type": "blog.post.revisions" },
          { "id": 2, "type": "blog.post.revisions" },
          { "id": 3, "type": "blog.post.revisions" },
          { "id": 4, "type": "blog.post.revisions" }
        ]
      },
      "current": {
        "data": { "id": 4, "type": "blog.post.revisions" }
      }
    }
  }]
}

Note: I removed most of the elements in the data property and removed the included property as they make the example unnecessarily large. Also don't worry about the type names, admittedly they look pretty weird but that's how I setup my serialiser (to reflect the pod structure).

请求它的路线看起来像这样

import Ember from 'ember';


export default Ember.Route.extend({
  model () {
    const store = this.get('store');
    return store.query('blog.post', { size: 10 });
  }
});

我所做的是通过用链接 属性 中指定的链接中的数据替换模型来为我的博客创建分页机制。

如何访问此 "links" 属性?


版本

解决方案

我最终扩展了序列化程序并在记录数组规范化后将 links 对象插入到 meta 对象中。

// pods:    app/application/serialiser.js
// vanilla: app/serialisers/application.js
import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({
  /**
   * will attach links to the meta object
   */
  normalizeArrayResponse (...args) {
    const normalized = this._super(...args);
    //
    // since the meta object is optional, it's
    // best to verify if it's null/undefined
    //
    if (normalized.meta == null) {
      normalized.meta = {};
    }
    normalized.meta.links = normalized.links;
    return normalized;
  }
});

所以在我的路线中我可以像这样访问对象的链接

import Ember from 'ember';

export default Ember.Route.extend({
  model (params) {
    const store = this.get('store');
    return store.query('blog.post', params).then(posts => {
      //
      // access the links object like so.
      //
      const links = posts.get('meta.links');
      return Ember.Object.create({ links, posts })
    });
  }
});

注意事项

这不是最佳解决方案,因为它可能会覆盖 meta 对象中任何名为 links 的 属性。

解决这个问题的一种方法是使用符号作为字段名称,因为符号是唯一的,因此您可以确定不会覆盖对象名称空间中的任何现有名称。但我还没有尝试过,它可能不会在旧浏览器上运行得很好,我不确定 ember 的 get 方法如何与符号交互。