简体   繁体   中英

graphql JS returns null when i send a query via graphiql

I think I have thoroughly checked this code but can't find the error please help!! I get a null return when I query id

also, vscode tells me my parent in the resolve function is not used. What am I doing wrong here??

express ---

const express = require('express');
const graphqlHTTP = require('express-graphql');
const schema = require('./schema/schema')

const app = express();

app.use('/graphql', graphqlHTTP({

  schema,
  graphiql:true

}));


app.listen(1991, ()=> {
   console.log('1991 live');
});

schema --

const graphql = require('graphql');
const _= require('lodash');

const { GraphQLObjectType, GraphQLString, GraphQLID, GraphQLInt, 
GraphQLSchema } = graphql;

var drugs = [

{name: 'Paracetamol', price: 200, qty: 20, drugid: 1},
{name: 'Amoxicilin', price: 700, qty: 10, drugid: 2}

];

var categories = [

{name: 'Painkiller', id: 1},
{name: 'Anti-Biotic', id: 2}

];


const DrugType = new GraphQLObjectType({

name: 'Drug',
fields: () => ({
    name: {type: GraphQLString},
    price: {type: GraphQLInt},
    qty: {type: GraphQLInt},
    drugid: {type: GraphQLID}
  })

});

const DrugCategory = new GraphQLObjectType({

name: 'Category',
fields: () => ({
    name: {type: GraphQLString},
    id: {type: GraphQLID}
  })

});

const RootQuery = new GraphQLObjectType({

name: 'RootQueryType',
fields: {
    drug:{
        type: DrugType,
        args:{id:{type: GraphQLID}},
        resolve(parent, args){
           return _.find(drugs, {drugid:args.id});

        }
    },

    category:{
        type: DrugCategory,
        args:{id: {type: GraphQLID}},
        resolve(parent,args){
            return _.find(categories, {id:args.id});
          }
      }
  }

});

module.exports = new GraphQLSchema({
  query: RootQuery
});

this is the result i get when i query in graphiql

query --

 {
 drug(id: 1){
   name
 }

}

result --

{
 "data": {
   "drug": null
  }
}

The object you're passing in to lodash's find method is { id: args.id } -- that means you're looking for an object with an id property that matches args.id . However, none of the objects in your drugs array have an id property. Either update your array or change your search criteria (ie { drugid: args.id } ).

Additionally, your type for the id argument is GraphQLID , which is treated like a String. That means find is comparing a String argument to a Number property value. Either change the argument's type to GraphQLInt , or wrap args.id with Number.parseInt , or change the drugId values to strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM