我正在尝试反序列化分页的终点。该终点的退货请求如下

{
    count: number,
    next: string,
    previous: string,
    data: Array[Objects]
}


我在使用js-data执行findAll时遇到的问题是将这个对象注入到数据存储中。它应该将数据数组中的对象注入到存储中。因此,我在适配器上做了一个反序列化方法,如下所示。

deserialize: (resourceConfig:any, response:any) => {
  let data = response.data;
  if (data && 'count' in data && 'next' in data && 'results' in data) {
    data = data.results;
    data._meta = {
      count: response.data.count,
      next: response.data.next,
      previous: response.data.previous
    };
  }
  return data;
}


这可行。数组对象被注入到我的数据存储中。但是元信息正在丢失。

dataStore.findAll('User').then(r => console.log(r._meta)); // r._meta == undefined


我想将该元信息保留在返回的对象上。有任何想法吗?

最佳答案

要在v3中做到这一点,您只需要重写几个方法即可调整JSData的
处理来自分页端点的响应。最重要的两个
事情是要告诉JSData响应的嵌套属性是记录
以及哪个嵌套属性应添加到内存存储中(应为
在两种情况下都使用相同的嵌套属性)。

例:

const store = new DataStore({
  addToCache: function (name, data, opts) {
    if (name === 'post' && opts.op === 'afterFindAll') {
      // Make sure the paginated post records get added to the store (and
      // not the whole page object).
      return DataStore.prototype.addToCache.call(this, name, data.results, opts);
    }
    // Otherwise do default behavior
    return DataStore.prototype.addToCache.call(this, name, data, opts);
  }
});

store.registerAdapter('http', httpAdapter, { 'default': true });

store.defineMapper('post', {
  // GET /posts doesn't return data as JSData expects, so we've got to tell
  // JSData where the records are in the response.
  wrap: function (data, opts) {
    // Override behavior of wrap in this instance
    if (opts.op === 'afterFindAll') {
      // In this example, the Post records are nested under a "results"
      // property of the response data. This is a paginated endpoint, so the
      // response data might also have properties like "page", "count",
      // "hasMore", etc.
      data.results = store.getMapper('post').createRecord(data.results);
      return data
    }
    // Otherwise do default behavior
    return Mapper.prototype.wrap.call(this, data, opts);
  }
});

// Example query, depends on what your backend expects
const query = { status: 'published', page: 1 };
posts.findAll(query)
  .then((response) => {
    console.log(response.results); // [{...}, {...}, ...]
    console.log(response.page); // 1
    console.log(response.count); // 10
    console.log(response.hasMore); // true
  });

关于javascript - js-data v3-将元信息保留在分页的端点中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38753593/

10-11 14:54