gpt4 book ai didi

javascript - js-data v3-将元信息保存在分页端点中

转载 作者:行者123 更新时间:2023-11-29 21:20:05 26 4
gpt4 key购买 nike

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

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

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

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;
}

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com