【发布时间】:2021-01-06 20:58:48
【问题描述】:
我正在为我的 React 前端使用 Apollo 客户端,以便能够使用由 Laravel Lighthouse 托管的 GraphQL。
正常用例有效,但我现在发现自己面临某些情况,我想在初始页面请求中预获取 GraphQL 结果,而不是让浏览器加载页面然后发送单独的 ajax 查询.
我看到Apollo client 支持“存储补水”和“服务器端渲染”,但我在 Lighthouse 中没有找到任何关于如何做到这一点的文档。
我认为我的 Blade 视图需要包含以下内容:
<script>
window.__APOLLO_STATE__ = '{!!$postsGqlResultJson ?? "null" !!}'; // https://www.apollographql.com/docs/react/performance/server-side-rendering/
</script>
那么问题来了:如何生成$postsGqlResultJson?
更新:
假设我在前端:
const POSTS = gql`
query Posts($first: Int, $page: Int) {
posts(first: $first, page: $page, orderBy: { field: CREATED_AT, order: DESC }) {
paginatorInfo {
currentPage
hasMorePages
total
}
data {
id
...
}
}
`;
const options = {
variables: {
first: 100,
page: 1,
}
};
const { loading, error, data } = useQuery(query, options);
我认为 Lighthouse 可能会提供某种与 useQuery 等效的 PHP 函数,我可以在其中以某种方式提供相同的参数(POSTS gql 和选项对象),并且它会返回结果数据的 JSON 字符串, 嵌套如 GQL 中所述。
我是不是误会了?我真的很感谢你的帮助。 :-)
【问题讨论】:
-
SR 和 SSR 选项用于预缓存/预渲染前端/react 应用程序状态/不同 url/路由的视图 - 在 gatsby 中用于 SEO 原因的模式/技术(可能的完整静态内容)或 nextjs ...您的前端/反应应用程序是如何提供服务的?
-
@xadm 我的后端是 Laravel Lighthouse (PHP)。
-
@xadm 这很酷,我喜欢 Spatie,但我问的是如何(从 Laravel 而不是 JS 中的任何地方,例如 Apollo)调用生成 GraphQL JSON 结果的 Lighthouse 函数.谢谢。
-
然后编辑标题/问题 .... 您正在寻找像 github.com/softonic/graphql-client 这样的“php graphql 客户端”
标签: graphql react-apollo apollo-client laravel-lighthouse