Next.js getServerSideProps中Apollo Client用SchemaLink查询报错求助
解决方案
1. 为SchemaLink指定Apollo Server的execute函数
SchemaLink默认执行逻辑可能无法兼容Nexus生成的可执行schema,需显式传入Apollo Server的execute方法:
if (typeof window === 'undefined') { const { SchemaLink } = require('@apollo/client/link/schema') const { schema } = require('./nexusSchema') const { execute } = require('@apollo/server') return new SchemaLink({ schema, execute }) }
2. 传入解析器所需的上下文
若你的Nexus解析器依赖特定上下文对象,需在SchemaLink创建或查询时传入:
方式一:创建SchemaLink时指定全局上下文
return new SchemaLink({ schema, execute, context: () => ({ // 填入解析器需要的上下文,如数据库实例、用户信息等 db: yourDbInstance, }) })
方式二:查询时传入上下文
const { data } = await apolloClient.query({ query: gql`...`, variables: { id }, context: { // 传入解析器依赖的上下文内容 } })
3. 降级Apollo Client版本
3.7.x版本的SchemaLink可能存在兼容性bug,可尝试降级至3.6.x版本(如3.6.9):
修改package.json中的依赖版本:
"@apollo/client": "^3.6.9",
重新安装依赖:
npm install # 或 yarn install
4. 检查Nexus Schema生成逻辑
确保nexusSchema.js中导出的schema是通过makeSchema生成的完整可执行schema:
// nexusSchema.js示例 import { makeSchema } from 'nexus' import * as types from './types' export const schema = makeSchema({ types, outputs: { schema: __dirname + '/../schema.graphql', typegen: __dirname + '/generated/nexus-typegen.ts', }, })
内容的提问来源于stack exchange,提问作者etteryand0
相关产品推荐
相关产品推荐

