GraphQL - return calculated type dependent on argument(GraphQL - 根据参数返回计算类型)
问题描述
概述(简化版):
在我的 NodeJS 服务器中,我实现了以下 GraphQL 架构:
In my NodeJS server I've implemented the following GraphQL schema:
客户端查询然后传递一个名称数组作为参数:
The client query then passes an array of names, as an argument:
后端 API 查询 mysql 数据库,以获取total"和active"字段(我的数据库表中的列)并减少响应,如下所示:
The backend API queries a mysql DB, for the "total" and "active" fields (columns on my DB table) and reduces the response like so:
<小时>
我希望我的 graphQL API 支持比率"项,即:我想发送以下查询:
I would like my graphQL API to support "ratio" Item, I.E: I would like to send the following query:
或
并返回 active/total 作为该新字段的计算结果 ([{"name":"ratio" , value:0.5}]
).以不同方式处理ratio"字段的通用方法是什么?
And return active / total as the calculated result of that new field ([{"name":"ratio" , value:0.5}]
). What would be a generic way to handle the "ratio" field differently?
它应该是我模式中的新类型还是我应该在 reducer 中实现逻辑?
Should it be a new type in my schema or should I implement the logic in the reducer?
推荐答案
Joe's answer (append {"name":"ratio" , value:data.active/data.total}
to the result一旦从数据库中获取结果)将在不进行任何架构更改的情况下进行.
Joe's answer (append {"name":"ratio" , value:data.active/data.total}
to the result once the result is fetched from database) would do it without making any schema changes.
作为替代方法或更优雅的 GraphQL 方法,可以在类型本身中指定字段名称,而不是将它们作为参数传递.并通过编写解析器来计算 ratio
.
As an alternative method or as a more elegant way to do it in GraphQL, the field names can be specified in the type itself instead of passing them as arguments. And compute ratio
by writing a resolver.
因此,GraphQL 架构将是:
So, the GraphQL schema would be:
客户端指定字段:
和 ratio
可以在解析器内部计算.
And ratio
can be calculated inside the resolver.
代码如下:
这篇关于GraphQL - 根据参数返回计算类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!