首页 > 解决方案 > 从 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也考虑更大的数据。帖子和计数是示例。例如用户帖子和用户评论。

标签: javascriptreactjsgraphql

解决方案


两种方法都是正确的!选择更好的方法取决于您的应用程序!

count通常比获取数据更快(有人可能会把它搞砸!:D),所以如果你单独获取它,你可以在你的帖子仍在加载时更快地显示它。

顺便说一句,GQLPromise自己处理!所以不需要那个异步等待!


推荐阅读