0

I have the following arrangement:

const Person = function(name, age, interest) {
    this.name = name;
    this.age = age;
    this.interest = interest;
}

const people = [
    new Person("rajat", 29, ['prog','food','gym']),
    new Person("ravi", 23, ['travel', 'cook', 'eat']),
    new Person("preeti", 19,  ['comedy', 'arts', 'beauty'])
];

const schema = buildSchema(`
    type Person {
        name: String,
        age: Int,
        interest: [String]
    },
    type Query {
        hello: String,
        giveTen(input: Int!): Int,
        person(name: String!): Person!, 
    }
`);

const root = {
    hello: () => 'Hello World',
    giveTen: (args) => args.input * 10,
    person: (args) => people.filter(item => item.name === args.name),
};

When I run the following query:

query PersonDetails {
  person(name: "rajat") {
    name
    age
    interest
  }
}

I get bunch of nulls, when there clearly is matching data in people array.

{
  "data": {
    "person": {
      "name": null,
      "age": null,
      "interest": null
    }
  }
}

1 Answer 1

1

What you return inside your resolver needs to match the type for that particular field. Inside your schema, you've specified the Root Query field person should return a Person type, not a List (array) of that type.

Array.prototype.filter() always returns an array.

If you want to return a single object from people, you should use Array.prototype.find() instead, which will return the first element that matches the test (or null if none are found).

If you want to return all possible matches, you'll need to change your schema to reflect that (change the return type from Person to [Person]). Then you can keep using filter and it should work as expected.

Sign up to request clarification or add additional context in comments.

1 Comment

I should have read more about Array.prototype.filter(). Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.