GraphQL - 返回依赖于参数的计算类型

Shl*_*rtz 12 mysql schema reducers node.js graphql

概述(简化):

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

type Item {
  name: String,
  value: Float
}


type Query {
  items(names: [String]!): [Item]
}
Run Code Online (Sandbox Code Playgroud)

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

{
  items(names: ["total","active"] ) {
    name
    value
  }
}
Run Code Online (Sandbox Code Playgroud)

后端API查询mysql DB,查看" total "和" active "字段(我的数据库表上的列)并减少响应,如下所示:

[{"name":"total" , value:100} , {"name":"active" , value:50}]
Run Code Online (Sandbox Code Playgroud)

我想我的graphQL API支持"比例"项目,IE:我想发送以下查询:

{
  items(names: ["ratio"] ) {
    name
    value
  }
}
Run Code Online (Sandbox Code Playgroud)

要么

{
  items(names: ["total","active","ratio"] ) {
    name
    value
  }
}
Run Code Online (Sandbox Code Playgroud)

并返回active/total作为该新字段([{"name":"ratio" , value:0.5}])的计算结果.以不同方式处理" 比率 "字段的通用方法是什么?

它应该是我的架构中的新类型还是应该在reducer中实现逻辑?

Ble*_*ess 5

Joe 的回答({"name":"ratio" , value:data.active/data.total}一旦从数据库中获取结果后附加到结果中)将在不进行任何架构更改的情况下完成。

作为在 GraphQL 中执行此操作的另一种方法或更优雅的方法,可以在类型本身中指定字段名称,而不是将它们作为参数传递。并ratio通过编写解析器进行计算。

因此,GraphQL 架构将是:

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

type Query {
  items: [Item]
}
Run Code Online (Sandbox Code Playgroud)

客户端指定字段:

{
  items {
    total 
    active 
    ratio
  }
}
Run Code Online (Sandbox Code Playgroud)

并且ratio可以在解析器内部进行计算。

这是代码:

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)))
Run Code Online (Sandbox Code Playgroud)