Prof3ssa
Prof3ssa

Reputation: 23

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
  }
}

Upvotes: 2

Views: 275

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84657

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 (i.e. { 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.

Upvotes: 1

Related Questions