2

我正在尝试反序列化分页端点。这个端点的返回请求看起来像

{
    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

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

4

1 回答 1

2

要在 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
  });
于 2016-10-21T15:01:51.897 回答