graphql - 在 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 相乘以创建结果。
解决方案
这不是 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 }
}
}
推荐阅读
- c - 如何使用带有可变数量参数的标记粘贴运算符?
- python - TypeError:不能在类似字节的对象上使用字符串模式?这个程序会出现以下错误,为什么?
- angular - 仅测试是否调用了 ngrx 操作就足够了吗?(单元测试)
- python - 在 Python 中快速将长音频文件转换为文本
- r - 使用带有参考书目风格的 natbib 的 RStudio 进行引用时出现问题
- php - 交替查询多个 Wordpress 帖子类型
- python - 如何在使用 python 抓取期间有效地解析大型列表数据?
- laravel - 仅在需要时使用 Echo 在 Laravel-Vue js 应用程序中建立与 Pusher 的连接
- c - 当我们将动态数组作为参数传递给函数时,为什么要使用双指针?
- javascript - parseInt NaN 输出。保存到火库