使用 node 和 graphql 返回一个字符串数组

Returning an array of Strings with node and graphql

我正在使用节点和 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
    }
  }
}

任何人都可以帮助我解决我在这里遗漏或做错的问题。

您的 keyValue 查询具有 return 类型 KeyValue

KeyValue 被声明为具有类型为 [String].

的字段 value

所以 keyValueData 应该 return 类型 KeyValue 而不是 [String].

的结果

您应该从 return result 更改为

return { value: result }