乔的回答(附加{"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)))