3

我想我已经彻底检查了这段代码,但找不到错误请帮忙!!查询 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
  }
}
4

1 回答 1

1

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

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

于 2018-10-03T11:24:50.533 回答