首页 > 解决方案 > 在 GraphQL 查询和模式中表示计算/脚本函数

问题描述

我们使用 GraphQL 作为数据聚合引擎的​​查询语言。

我正在寻找在 GraphQL 中表示简单(或复杂)算术计算函数的想法,这些函数指的是模式中定义的现有类型/属性,并且可以用于现有属性。

我正在研究自定义标量和指令

例子 -

{
    item{
        units
        price_per_unit
        market_price: function:multiply(units, price_per_unit)
        market_price_usd: function:usdPrice(units, price_per_unit, currency)
    }
}

其中 function:multiply 已在GraphQL模式中定义为类型

functions {
    multiply(operand 1, operand2) {
        result
    }
    usdPrice(operand1, operand2, currency) {
        result: {
                if(currency == GBP) {
                    operand1 * operand2 * .76
                }
            {
    }

内部解析器将操作数 1 和操作数 2 相乘以创建结果。

标签: graphqlgraphql-java

解决方案


这不是 GraphQL 特别擅长的。到目前为止,最简单的事情是检索各个字段,然后在客户端上进行计算,例如

data.item.forEach((i) => { i.total_price = i.units * i.price_per_unit });

特别是,无法在 GraphQL 中运行任何类型的“子查询”。给定一个像你展示的“乘法”函数,没有 GraphQL 语法可以让你用任何特定的输入“调用”它。

如果您认为特定的计算值足够常见,您还可以将它们添加到 GraphQL 模式中,并在需要时使用自定义解析器函数在服务器端计算它们。

type Item {
  units: Int!
  pricePerUnit: CurrencyValue!
  # computed, always units * pricePerUnit
  marketPrice: CurrencyValue!
}
type CurrencyValue {
  amount: Float!
  currency: Currency!
  # computed, always amount * currency { usd }
  usd: Float!
}
type Currency {
  code: String!
  "1 currency = this many US$"
  usd: Float!
}

允许查询

{
  item {
    marketPrice { usd }
  }
}

推荐阅读