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

2024-04-16

Overview(简化):

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

type Item {
  name: String,
  value: Float
}


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

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

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

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

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

我希望我的 graphQL API 支持“ratio”项,即:我想发送以下查询:

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

or

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

并返回活跃/总计作为该新字段的计算结果([{"name":"ratio" , value:0.5}])。处理“的通用方法是什么?ratio“ 领域不同?

它应该是我的模式中的新类型还是应该在减速器中实现逻辑?


乔的回答(附加{"name":"ratio" , value:data.active/data.total}从数据库获取结果后)将在不进行任何模式更改的情况下完成此操作。

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

因此,GraphQL 架构将是:

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

type Query {
  items: [Item]
}

客户端指定字段:

{
  items {
    total 
    active 
    ratio
  }
}

And 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)))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

GraphQL - 根据参数返回计算类型 的相关文章

随机推荐