Search code examples
javascriptnode.jsgraphqlexpress-graphql

graphql-JS Express cannot resolve a field


When I execute the below code in node server. I see an error that graphql-JS cannot resolve the field "product.productTax."

Using graphql-express, visual studio code, I was trying to exactly mimic the following code from 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');

Response Graphiql Response


Solution

  • In your schema you have

        productTax(tax_rate: Float!): [Float!]
    

    so graphql is expecting an array of float values. It seems that it should be

        productTax(tax_rate: Float!): Float!
    

    since your productTax() method is returning one float value.

    You can also add default tax rate. I don't see you are passing it anyway, so

        productTax(tax_rate: Float = 20): Float!