Daniel
Daniel

Reputation: 7172

GraphQL: referencing other ids

I have a series of tables like:

Person:
person_id
first_name
last_name

CompanyPerson
person_id
company_id

Company
company_id
name

OfficePerson
office_id
person_id

Office
office_id
company_id
address_1
address_2
...

How would I indicate to graphQL, that I the following information: firstName is "Joe", company name, office addresses (ONLY office addresses for which JOE belongs to).

people(firstName: "joe") {
  company {
    name
    office {
      address_1
      address_2
    }
  }
}

If this was a singular request, I could set the "context" to talk about "joe"

person(firstName: "joe") {
}

I could use the graphql query schema to add further context restrictions (user: "Joe")

Since this is for multiple people, I don't see a method further refining queries based on information provided in a previous object.

Using: Ruby latest; graphql-ruby latest;

Thank you,

-daniel

Upvotes: 0

Views: 820

Answers (1)

Greg Brodzik
Greg Brodzik

Reputation: 1817

A resolver function receives four argument, one of which is the obj -- the object returned from the previous field. For example, a resolver map could appear as followers, in relevant part:

    // Root query/entry pt.
    Query: {
        async user(obj, input, context) {
          try 
            return user; // returns type User
          } catch (e) {
           console.log('err', e);
          }
        },

   ......
    // NOT a root query/entry pt.
    User: {
        async followers(obj, input, context) {
          try {
           const followers = await getFollowersByUserId(obj.id);
           return followers;
          } catch (e) {
            console.log('err', e);
          }
       },

Above, after the root query for user returns, graphql knows to look to resolve fields on the User type -- in this case, for example, followers. The returned value from the user root query is available as the obj and can be used to resolve fields on User. This should hold true whether the query is resolving a single User, or an array of type User. While the above is in js this should hold true for ruby, although your schema may need ot be modified.

Upvotes: 1

Related Questions