GraphQL - 根据参数返回计算类型

2022-01-04 00:00:00 node.js graphql schema mysql reducers

概述(简化版):

在我的 NodeJS 服务器中,我实现了以下 GraphQL 架构:

In my NodeJS server I've implemented the following GraphQL schema:

type Item {
  name: String,
  value: Float
}


type Query {
  items(names: [String]!): [Item]
}

客户端查询然后传递一个名称数组作为参数:

The client query then passes an array of names, as an argument:

{
  items(names: ["total","active"] ) {
    name
    value
  }
}

后端 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:

[{"name":"total" , value:100} , {"name":"active" , value:50}]

<小时>

我希望我的 graphQL API 支持比率"项,即:我想发送以下查询:


I would like my graphQL API to support "ratio" Item, I.E: I would like to send the following query:

{
  items(names: ["ratio"] ) {
    name
    value
  }
}

{
  items(names: ["total","active","ratio"] ) {
    name
    value
  }
}

并返回 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:

Item {
  total: Int,
  active: Int,
  ratio: Float
}

type Query {
  items: [Item]
}

客户端指定字段:

{
  items {
    total 
    active 
    ratio
  }
}

ratio 可以在解析器内部计算.

And ratio can be calculated inside the resolver.

代码如下:

const express = require('express');
const graphqlHTTP = require('express-graphql');
const { graphql } = require('graphql');
const { makeExecutableSchema } = require('graphql-tools');
const getFieldNames = require('graphql-list-fields');

const typeDefs = `
type Item {
  total: Int,
  active: Int,
  ratio: Float
}

type Query {
  items: [Item]
}
`;

const resolvers = {
  Query: {
    items(obj, args, context, info) {
      const fields = getFieldNames(info) // get the array of field names specified by the client
      return context.db.getItems(fields)
    }
  },
  Item: {
    ratio: (obj) => obj.active / obj.total // resolver for finding ratio
  }
};

const schema = makeExecutableSchema({ typeDefs, resolvers });

const db = {
  getItems: (fields) => // table.select(fields)
    [{total: 10, active: 5},{total: 5, active: 5},{total: 15, active: 5}] // dummy data
}
graphql(
  schema, 
  `query{
    items{
      total,
      active,
      ratio
    }
  }`, 
  {}, // rootValue
  { db } // context
).then(data => console.log(JSON.stringify(data)))

相关文章