【问题标题】:graphql JS returns null when i send a query via graphiql当我通过 graphiql 发送查询时,graphql JS 返回 null
【发布时间】:2019-03-08 14:29:26
【问题描述】:

我想我已经彻底检查了这段代码,但找不到错误,请帮忙!! 当我查询 id 时,我得到一个空返回

另外,vscode 告诉我我的父母在 resolve 函数中没有使用。我在这里做错了什么??

快递---

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');
});

架构 --

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

这是我在graphiql中查询得到的结果

查询 --

 {
 drug(id: 1){
   name
 }

}

结果 --

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

【问题讨论】:

标签: javascript express schema express-graphql


【解决方案1】:

您传递给 lodash 的 find 方法的对象是 { id: args.id }——这意味着您正在寻找一个具有与 args.id 匹配的 id 属性的对象。但是,drugs 数组中的所有对象都没有id 属性。更新您的数组或更改您的搜索条件(即{ drugid: args.id })。

此外,id 参数的类型是 GraphQLID,它被视为字符串。这意味着find 正在将 String 参数与 Number 属性值进行比较。将参数的类型更改为GraphQLIntargs.id换成Number.parseIntdrugId的值更改为字符串。

【讨论】:

  • 我已经更新了 lodash 方法,但是在我添加 drugid 之前,我仍然得到空值,它只是 {id:args.id} 并且仍然没有工作。你认为我还缺少其他东西吗??
  • 你的新方法调用是什么样的?
  • 我更新了问题中的代码,但现在看起来像这样.. return _.find(drugs, {drugid:args.id});
  • 糟糕。刚刚注意到您的论点的类型是GraphQLID。请查看更新后的答案。
  • 在更改为字符串后,我在查询时没有收到TypeError: Failed to fetch 错误.. omg 我真的很头疼..
猜你喜欢
  • 1970-01-01
  • 2019-06-14
  • 2020-01-07
  • 2020-01-15
  • 2021-01-15
  • 2022-01-04
  • 1970-01-01
  • 2020-03-01
相关资源
最近更新 更多