Roger Ko
Roger Ko

Reputation: 197

Apollo Graphql Resolver for a Nested Object

So I have a type like this:

type CardStatus {
  status: String
  lastUpdated: String
}

type CardCompany {
  cardStatus: CardStatus
}

type ExternalAccounting {
  cardCompany: CardCompany
}

type User {
  balance: String
  externalAccounting: ExternalAccounting
}

And my resolver looks something like this

const User = {
  balance: (root, args, context) => getBalance().then((res)=>res)
  cardStatus: (??)
}

I want to use a resolver to set the nested cardStatus field in the user object.

Balance is the direct field of an object, it's easy- I just run a resolver and return the result to get balance. I want to run a cardStatus api call for the deeply nested cardStatus field, but I have no idea how to do this. I've tried something in my resolver like this:

  const User = {
    balance: {...}
    externalAccounting: {
      cardCompany: {
        cardStatus: (root) => { (...) },
      },
    },
  }

But it doesn't work in that it does not set the cardStatus nested field of the user object. Seems like it should be relatively easy but I can't find an example online..

Upvotes: 1

Views: 3801

Answers (1)

Tal Z
Tal Z

Reputation: 3210

You should define the cardStatus resolver under the type CardCompany.

When defining types, they should all be on the same level in the resolver map. Apollo will take care of resolving the query's nested fields according to the type of each nested field.

So your code should look something like this:

const User = {
  balance: (root, args, context) => getBalance().then((res)=>res)
}

const CardCompany = {
  cardStatus: (root) => { (...) },
}

And I'm not sure how it is connected to your executable schema but it should probably be something similar to:

const schema = makeExecutableSchema({
  typeDefs,
  resolvers: merge(User, CardCompany, /* ... more resolvers */ )
})

Upvotes: 3

Related Questions