我正在尝试基于 Ben Awad 课程的类似 reddit 的网络应用程序。我在单个帖子页面中添加了评论部分。我对帖子和评论都有光标分页。这就是它的外观:
const cursorCommentsPagination = (): Resolver => {
return (_parent, fieldArgs, cache, info) => {
const { parentKey: entityKey, fieldName } = info;
const allFields = cache.inspectFields(entityKey);
const fieldInfos = allFields.filter(
(info) =>
info.fieldName === fieldName &&
info.arguments!.postId ===
parseInt(stringifyVariables(fieldArgs.postId)) // taking only posts with this postId
);
const size = fieldInfos.length;
if (size === 0) {
return undefined;
}
const fieldKey = `${fieldName}(${stringifyVariables(fieldArgs)})`;
const isItInTheCache = cache.resolve(entityKey, fieldKey) as string;
info.partial = !isItInTheCache;
let hasMore = true;
const results: string[] = [];
fieldInfos.forEach((fi) => {
const key = cache.resolve(entityKey, fi.fieldKey) as string;
const data = cache.resolve(key, "comments") as string[];
const _hasMore = cache.resolve(key, "hasMore");
if (!_hasMore) {
hasMore = _hasMore as boolean;
}
results.push(...data);
});
return {
__typename: "PaginatedComments",
hasMore,
comments: results,
};
};
};
由于某种原因,它工作起来很奇怪 - 它缓存了我访问的每个帖子页面中的每条评论,并在我访问的下一篇文章中显示所有缓存的评论所以我决定添加这个:
...
parseInt(stringifyVariables(fieldArgs.postId)) // taking only posts with this postId
...
它工作正常。但它现在只缓存一个帖子中的评论,所以如果我去另一个帖子,缓存会重置,如果我返回并转到同一个帖子,缓存工作正常。现在我不确定,我是否需要缓存评论,或者有什么办法可以缓存所有评论,只在页面上只需要那些评论?