am0*_*100 5 graphql graphql-java
我们使用 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)
}
}
Run Code Online (Sandbox Code Playgroud)
其中 function:multiply 已在GraphQL架构中定义为类型
functions {
multiply(operand 1, operand2) {
result
}
usdPrice(operand1, operand2, currency) {
result: {
if(currency == GBP) {
operand1 * operand2 * .76
}
{
}
Run Code Online (Sandbox Code Playgroud)
内部解析器将操作数 1 和操作数 2 相乘以创建结果。
这并不是 GraphQL 特别擅长的事情。到目前为止,最简单的事情是检索各个字段,然后在客户端上进行计算,例如
data.item.forEach((i) => { i.total_price = i.units * i.price_per_unit });
Run Code Online (Sandbox Code Playgroud)
特别是,无法在 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!
}
Run Code Online (Sandbox Code Playgroud)
允许像这样的查询
{
item {
marketPrice { usd }
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1705 次 |
| 最近记录: |