当我在节点服务器中执行以下代码时。我看到graphql-JS无法解析字段“product.productTax”的错误。
使用graphql-express,visual studio代码,我试图完全模仿来自http://graphql.org/graphql-js/object-types/的以下代码
<!-- language: lang-js -->
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
type Product{
product_id: Int!
sku: String
short_nm: String
retl_price: Float!
productTax(tax_rate: Float!): [Float!]
}
type Query {
getproduct(product_id: Int, sku: String, short_nm: String, retl_price: Float): Product
}
`);
// This class implements the Product GraphQL type
class Product {
constructor(product_id, sku, short_nm, retl_price) {
this.product_id = product_id;
this.sku = sku;
this.short_nm = short_nm;
this.retl_price = retl_price;
}
productTax({tax_rate}){
return this.retl_price * tax_rate / 100;
}
}
// The root provides the top-level API endpoints
var root = {
getproduct: function ({product_id, sku, short_nm, retl_price}) {
return new Product(product_id, sku, short_nm, retl_price);
}
}
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');
答案 0 :(得分:1)
在您的架构中,您有
productTax(tax_rate: Float!): [Float!]
因此graphql期望一个浮点值数组。它似乎应该是
productTax(tax_rate: Float!): Float!
因为您的productTax()
方法返回一个浮点值。
您还可以添加默认税率。我还没有看到你传递它,所以
productTax(tax_rate: Float = 20): Float!