You need to enable JavaScript to run this app. 如何在基于FSharp.Data.GraphQL的F# GraphQL服务中通过context跨resolver共享数据?
优惠活动
大模型
产品
解决方案
定价
更多

如何在基于FSharp.Data.GraphQL的F# GraphQL服务中通过context跨resolver共享数据?

FSharp.Data.GraphQL 跨Resolver共享上下文实现方案

核心逻辑和Node.js生态的GraphQL context完全对齐:每个请求执行时生成独立的上下文实例,所有Resolver共享同一份请求级数据,且不会跨请求污染。由于F#是静态类型语言,推荐通过强类型自定义上下文实现,避免动态对象的运行时错误。

具体实现步骤

1. 定义自定义上下文类型

把所有需要跨Resolver共享的请求级数据(如当前用户、数据库连接、请求ID等)定义为可序列化的F# record类型:

type RequestGraphQLContext = {
    // 示例共享数据,可根据业务自定义
    ScopedDbContext: AppDatabaseContext
    CurrentUser: UserInfo option
    RequestTraceId: string
}

2. 定义Resolver时声明上下文类型

构建Schema时,字段的resolve函数会接收带泛型的字段上下文参数,可直接从中拿到自定义的请求上下文:

open FSharp.Data.GraphQL
open FSharp.Data.GraphQL.Types

// 定义业务类型示例
let UserType = Define.Object<UserInfo>(name = "User", fields = [
    Define.Field("id", Int, resolve = fun ctx user -> user.Id)
    Define.Field("name", String, resolve = fun ctx user -> user.Name)
])

let OrderType = Define.Object<Order>(name = "Order", fields = [
    Define.Field("id", Int, resolve = fun ctx order -> order.Id)
    Define.Field("amount", Float, resolve = fun ctx order -> order.Amount)
])

// 定义根Query类型
let QueryType = Define.Object<unit>(name = "Query", fields = [
    // 获取当前登录用户
    Define.Field("me", Nullable UserType, resolve = fun (ctx: ResolveFieldContext<RequestGraphQLContext, unit>) _ ->
        ctx.Context.CurrentUser
    )

    // 获取当前用户的订单列表,复用同一份上下文的Db和CurrentUser数据
    Define.Field("myOrders", ListOf OrderType, resolve = fun (ctx: ResolveFieldContext<RequestGraphQLContext, unit>) _ ->
        match ctx.Context.CurrentUser with
        | Some user -> ctx.Context.ScopedDbContext.GetOrdersByUserId(user.Id) |> List.ofSeq
        | None -> []
    )
])

// 初始化Schema
let schema = Schema(QueryType)

3. 执行查询时传入自定义上下文

处理GraphQL请求时,从当前请求的上下文(如HTTP请求头、用户认证信息、DI容器的Scoped服务)中提取数据,构造RequestGraphQLContext实例,传入执行选项:

// 以Web请求处理为例
let processGraphQLRequest (httpRequest: HttpRequest) (query: string) =
    task {
        // 从HTTP请求中提取数据构造共享上下文
        let requestContext = {
            ScopedDbContext = dbContextFactory.Create() // 从DI容器拿到请求级Scoped数据库实例
            CurrentUser = httpRequest.TryGetAuthenticatedUser() // 从请求头解析当前登录用户
            RequestTraceId = httpRequest.TraceIdentifier
        }

        // 构造执行选项,传入自定义上下文
        let execOptions = ExecutionOptions<RequestGraphQLContext>(
            query = query,
            Context = requestContext
        )

        // 执行查询并返回结果
        let! result = schema.AsyncExecute(execOptions)
        return result.ToJson()
    }

补充说明

  • 不推荐使用默认动态上下文的Items字典存共享数据,强类型自定义上下文可获得编译时类型检查,避免键名拼写错误、类型不匹配等运行时问题。
  • 上下文的生命周期和单个GraphQL请求对齐,每个请求生成独立的上下文实例,不会出现跨请求的数据污染,和Node.js的context行为完全一致。

内容的提问来源于stack exchange,提问作者Harshal Patil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.12.02 00:45:06