如何配置Laravel Lighthouse为GraphQL提供服务器端渲染



我使用Apollo客户端作为React前端,以便能够使用Laravel Lighthouse托管的GraphQL。

正常的用例是可行的,但我现在发现自己面临的某些情况是,我想在初始页面请求中预取GraphQL结果,而不是让浏览器加载页面,然后发送单独的ajax查询。

我看到Apollo客户端支持";储存再水化";以及";"服务器端渲染";,但我还没有在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和options对象(,它将返回结果数据的JSON字符串,如gql中所述嵌套。

我误解了吗?我真的很感谢你的帮助

您所描述的Apollo客户端功能看起来像是前端的问题,并假设您从Node.js服务器为前端提供服务。

在Lighthouse中没有什么特别的事情可做——从它的角度来看,查询是作为服务器端渲染的一部分发送还是从客户端发送都无关紧要。

最新更新