0

I am using node and graphql to get value (array of string) of a specific key. Following is the schema which is being used

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

From Client I am sending:

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

but it gives null always

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

Can anybody help me what I am missing here or doing wrong.

Mandeep Singh
  • 1,287
  • 14
  • 34
  • `keyValueData` has to return an object with the key `value` with an array in it, like this `return { value: result }`, but you are returning an array – thammada.ts May 10 '20 at 15:39
  • thanks man it worked,silly mistake, can you put it in answer, will give correct answer – Mandeep Singh May 10 '20 at 15:54

1 Answers1

0

Your keyValue query has a return type KeyValue.

KeyValue is declared to have a field value which is of type [String].

So keyValueData should return a result of type KeyValue not [String].

You should change from return result to

return { value: result }
thammada.ts
  • 5,065
  • 2
  • 22
  • 33