我正在学习Ben Awad的" Fullstack React GraphQL TypeScript教程";在youtube上。它已经有几年的历史了,所以我正忙着修改代码以使用更新的包,特别是这里的url -graphcache。
如果你也跟着看,我快到7点48分了。
我通读了关于cache.resolve()方法的文档。
这些是来自文档
的例子// This may resolve a link:
cache.resolve({ __typename: 'Query' }, 'todo', { id: 1 }); // 'Todo:1'
// This may also resolve records / scalar values:
cache.resolve({ __typename: 'Todo', id: 1 }, 'id'); // 1
// You can also chain multiple calls to `cache.resolve`!
cache.resolve(cache.resolve({ __typename: 'Query' }, 'todo', { id: 1 }), 'id'); // 1
这些例子并不能解释我在我的应用程序中碰巧为教程工作的行为。
//first resolve call
const res = cache.resolve("Query", "posts({"limit":10})") //Query.posts({"limit":10})
//second resolve call
const res2 = cache.resovle(res as Entity, 'posts') // [Post:1, Post:2, Post:3]
看起来cache.resolve()实际上是两个完全不同的函数的包装器。但为什么会是这样呢?
cache .resolve()第一个解析的是什么?作为实体的结果是怎样的?
是否有一种方法来构建调用,以便我只需要调用一次?
我遵循相同的课程,并根据github上的urql分页示例找到了解决方案。你可以直接把源代码中的resolveFieldByKey
换成resolve
,它的工作方式是一样的。
所以使用:
const isItInTheCache = cache.resolve(
cache.resolve(entityKey, fieldKey) as string,
"posts"
);
...
const key = cache.resolve(entityKey, fi.fieldKey) as string;
const data = cache.resolve(key, "posts") as string[];
作为最新包的一部分,我们需要使用cache.resolve()来查找键和相关数据。
返回类型,它需要与实际结果值的__typename
。当我们正在解析实体时
https://formidable.com/open-source/urql/docs/graphcache/local-resolvers/resolving-entities
const cursorPagination = (): Resolver<any, any, any> => {
return (_parent, fieldArgs, cache, info) => {
const { parentKey: entityKey, fieldName } = info;
console.log(entityKey, fieldName);
const allFields = cache.inspectFields(entityKey);
console.log('allfields ', allFields)
const fieldInfos = allFields.filter(info => info.fieldName === fieldName);
const size = fieldInfos.length;
if (size === 0) {
return undefined;
}
// Check if data is in cache and return it.
const fieldKey = `${fieldName}(${stringifyVariables(fieldArgs)})`;
const isItInTheCache = cache.resolve(
cache.resolve(entityKey, fieldKey) as string,
"posts"
);
console.log(fieldKey);
info.partial = !isItInTheCache;
const results: string[] = [];
fieldInfos.forEach(fi => {
const key = cache.resolve(entityKey, fi.fieldKey) as string;
const data = cache.resolve(key, "posts") as string[];
results.push(...data);
});
console.log("results",results);
return {
__typename: "PaginatedPosts",
posts: results,
};
};
};
希望这有帮助!