【问题标题】:Returning an array of Strings with node and graphql返回带有节点和graphql的字符串数组
【发布时间】:2020-08-26 02:17:05
【问题描述】:

我正在使用 node 和 graphql 来获取特定键的值(字符串数组)。以下是正在使用的架构

var schema = buildSchema(`
    type Query {
        keyValue(id: String!): KeyValue
    },
    type KeyValue {
      value: [String]
    }
`);

var tempArray = [{
   id:"1",
   value: ["ABC", "CDE", "1JUU", "CDE"]
},{
   id:"2",
   value: ["ABC", "CDE", "2JUU", "CDE"]
}];

var keyValueData = (args) => {
  var id = args.id;
  var result = null;
  for (let key of tempArray) {
    if (key.id === id) {
      result = key.value;
      break;
    }
  }
  console.log(result); // I see the result in the console as ["ABC", "CDE", "1JUU", "CDE"] when I send id as 1 from client
  return result;
}

var root = {
    keyValue: keyValueData
};

var app = express();
app.use('/graphql', express_graphql({
    schema: schema,
    rootValue: root,
    graphiql: true
}));
app.listen(4010, () => console.log('Running On localhost:4010/graphql'));

来自我发送的客户:

{
  keyValue(id: "1") {
    value
  }
}

但它总是给 null

{
  "data": {
    "keyValue": {
      "value": null
    }
  }
}

任何人都可以帮助我在这里缺少什么或做错了什么。

【问题讨论】:

  • keyValueData 必须返回一个带有键 value 的对象,其中包含一个数组,例如 return { value: result },但您返回的是一个数组
  • 谢谢大佬成功了,愚蠢的错误,你能把它放在答案中,会给出正确答案

标签: javascript graphql graphql-js express-graphql


【解决方案1】:

您的keyValue 查询的返回类型为KeyValue

KeyValue 被声明为具有 value 类型的字段 [String]

所以keyValueData 应该返回KeyValue 类型的结果而不是[String]

你应该从return result改为

return { value: result }

【讨论】:

    猜你喜欢
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 2012-12-07
    • 2015-05-24
    • 2015-06-21
    • 1970-01-01
    相关资源
    最近更新 更多