javascript - 从 Graphql 服务器获取数据的哪种方式更好?
问题描述
我有一个使用 React 作为客户端框架和 Graphql 来运行 API 的应用程序。计划正在获取用户帖子和帖子计数。
客户端
const Profile = () => (
<div>
<PostCount />
<Posts />
</div>
)
const PostCount = () => ...
const Posts = () => ...
我们需要在 Posts 组件中显示帖子,在 Count 组件中显示帖子数。所以我的问题是,哪个更好。
在一个请求中获取 Profile 组件中的所有数据,并将其作为 props 发送到 Post 和 Count 组件。或获取 Count 组件中的帖子计数和 Post 组件中的帖子。
场景一包括对服务器的一个请求和更大的数据块。
方案二包括对服务器的两个请求和较小的数据块。
场景一服务器端:
const schema = `
type Query {
feeds(): Feed!
}
type Feed {
posts: [Post!]!
count: Int!
}
type Post {
...
}
`
async function feed() {
const posts: await Post.findAll();
const count = await Post.count();
return {
count
posts,
}
}
场景二服务器端:
const schema = `
type Query {
posts(): [Post!]!
count(): Int!
}
type Post {
...
}
`
async function feed() {
const posts: await Post.findAll();
return posts;
}
async function count() {
const count = await Post.count();
return count;
}
PS也考虑更大的数据。帖子和计数是示例。例如用户帖子和用户评论。
解决方案
两种方法都是正确的!选择更好的方法取决于您的应用程序!
count
通常比获取数据更快(有人可能会把它搞砸!:D),所以如果你单独获取它,你可以在你的帖子仍在加载时更快地显示它。
顺便说一句,GQLPromise
自己处理!所以不需要那个异步等待!
推荐阅读
- php - 依赖N级下拉列表
- python - 如何在一个输入中包含多个字符串以在一行中打印?
- php - 如何使用 php 在 ftp 服务器上创建受密码保护的 zip 文件
- javascript - 排序对象列表javascript
- android - 如何按设备处理位图的大小:“密度独立或替代位图”
- php - Symfony \ Component \ Debug \ Exception \ FatalThrowableError(E_ERROR)类'APP \ Mail \ Reverify'未找到
- python - 我如何从 SQLite3 表中获取数据作为浮点数?它作为元组返回
- javascript - Firestore 和 Vue.js 多个 Where 子句
- javascript - 是什么导致我的 jQuery 调用出现这种递归?
- python - 如何使这个循环每次迭代增加 1.8?