【问题标题】:GraphQL - handle nested dataGraphQL - 处理嵌套数据
【发布时间】:2019-12-27 07:45:31
【问题描述】:

我的数据架构如下:

{
    instrumentName: String,
    lastPrice {
        bid: Float,
        ask: Float
    }
}

数据以 Json 格式存储在我的数据库中,例如:

{
    "instrumentName": "GOOGLE.N",
    "lastPrice": {
        "bid": 90.00,
        "ask": 105.00
    }
}

在 GraphQL 中,我必须将 graphQL 模式定义为:

type Instrument {
    instrumentName: String
    lastPrice: Price
}
type Price {
    bid: Float
    ask: Float
}

当我构建我的数据提取器时,仪器提取器很好。我只是从数据库中选择记录作为以前的示例数据。 但是当它递归地获取价格时,由于已经从 Instrument fetcher 的数据库中加载了买价/卖价,我想知道有没有办法“告诉”Price fetcher 关于以前的样本数据,例如,把数据进入 Price fetcher 的数据获取环境? 或者我可以定义一个不同的(嵌套的)graphQL 模式来处理这种情况吗?

【问题讨论】:

    标签: graphql


    【解决方案1】:

    我目前正在使用 apollo-server,至少有了这个(不知道其他 GraphQL 的实现),default resolver behaviour 应该为你处理这个问题,所以只需要一个数据库获取,前提是您的 instrument 提取器返回完整的数据结构:

    const resolvers = {
        Query: {
            instrument: (parent, args, context, info) => {
                instrumentName: "GOOGLE.N",
                lastPrice: {
                    bid: 90.00,
                    ask: 105.00
                }                    
            }
        },
    
        // Following resolver should not be needed as will be handled by default resolver
        //  Instrument: {
        //      lastPrice: (parent, args, context, info) => {
        //          ...
        //      }
        //  }
    }
    

    如果您使用的不是 apollo-server,我不确定上述是否成立。

    【讨论】:

    • 我正在使用 GraphQL-java。最后我发现所有东西都可以递归地描述为 Map 。所以它现在有效。谢谢约翰:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 2018-08-22
    • 2019-03-02
    相关资源
    最近更新 更多