Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to call another resolver in Apollo Server?

Say you wanted to call the createdAt resolver from the updatedAt resolver. For example this doesn't work:

{
  Review: {
    createdAt: review => review._id.getTimestamp(),
    updatedAt: review => review.updatedAt || this.createdAt(review)
  },
}

I realize I could make a reviewCreatedAt() function that is called from both, but I'm looking for a way to call the createdAt resolver.

like image 563
Loren Avatar asked May 31 '19 23:05

Loren


People also ask

What is a Gql resolver?

Resolver is a collection of functions that generate response for a GraphQL query. In simple terms, a resolver acts as a GraphQL query handler. Every resolver function in a GraphQL schema accepts four positional arguments as given below − fieldName:(root, args, context, info) => { result }

What is Apollo resolver?

Apollo Server needs to know how to populate data for every field in your schema so that it can respond to requests for that data. To accomplish this, it uses resolvers. A resolver is a function that's responsible for populating the data for a single field in your schema.

How does resolver work in GraphQL?

Each field on each type is backed by a function called the resolver which is provided by the GraphQL server developer. When a field is executed, the corresponding resolver is called to produce the next value. If a field produces a scalar value like a string or number, then the execution completes.


1 Answers

There is no standard way to call another resolver. Using this won't work even if you don't use an arrow function because the context is lost when the resolver is called by the underlying code. You can do something like this:

const resolvers = {
  Review: {
    createdAt: review => review._id.getTimestamp(),
    updatedAt: review => review.updatedAt || resolvers.Review.createdAt(review)
  },
}

If you're using a data model, though, you may find it easier to just lift this logic into the data model (using a calculated or virtual field).

like image 107
Daniel Rearden Avatar answered Jan 03 '23 01:01

Daniel Rearden