You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore集成GraphQL上下文传递异常:Resolver中ctx为空

解决Apollo Server v4中Firestore上下文传递为空的问题

问题描述

将Firebase Firestore集成到GraphQL的Apollo Server时,尝试在创建ApolloServer实例时传递Firestore作为上下文,但执行loginUser查询时,Resolver中的上下文对象ctx始终为空{}。已确认Firestore初始化完成(启动服务器时打印能得到正常实例),但上下文无法传递到Resolver。

问题原因

Apollo Server v4的startStandaloneServer模式下,不能在ApolloServer构造函数中配置context——该配置会被startStandaloneServer的选项覆盖。同时,startStandaloneServer要求context必须是一个函数(支持异步),而非直接的对象或错误的语法写法。

修复步骤

  1. 移除ApolloServer构造函数中的context配置
  2. 在startStandaloneServer的选项参数中添加context函数,返回包含Firestore的上下文对象
  3. 确保Resolver的参数顺序正确(第三个参数为上下文)

修改后的代码示例

index.js

import { ApolloServer } from '@apollo/server'
import { startStandaloneServer } from '@apollo/server/standalone'
import { typeDefs } from "./schema/typedefs/TypeDefs.js";
import { resolvers } from './schema/resolver/Resolvers.js'
import { initializeApp } from 'firebase/app'
import { getFirestore } from "firebase/firestore";

// 初始化Firebase
const firebaseConfig = {
    // 你的配置信息
};

const app = initializeApp(firebaseConfig)
const firestore = getFirestore(app)

// 移除构造函数中的context配置
const server = new ApolloServer({
    typeDefs,
    resolvers
})

await startStandaloneServer(
    server,
    {
        port: 4000,
        // 在这里配置context,必须是函数
        context: async () => {
            return { firestore };
        }
    })
    .then(({ url }) => {
        console.log(`Server running at ${url}`);
        console.log('Firestore实例已初始化:', firestore);
    })

resolver.js(无需修改,参数顺序正确)

export const resolvers = {
    Query: {
        loginUser: async (_, { email }, ctx) => {
            console.log(ctx); // 现在会输出包含firestore的对象
            return "String"
        }
    }
    // 其他Resolver...
}

原理说明

startStandaloneServer是Apollo Server v4提供的独立服务器启动方式,它会接管上下文的生成逻辑。将context定义为函数的好处是,不仅能传递全局的Firestore实例,还能在需要时获取请求相关的信息(如请求头、用户认证信息等),适配更复杂的场景。

内容的提问来源于stack exchange,提问作者noor.soreti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 14:32:38