Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In GraphQL is it possible to have resolvers on object type level?

We are working on quite a complicated GraphQL schema where we have several object types that belong to various micro services, where each object type has a natural API endpoint we can query. Therefore it would be quite convenient if it would be possible to define specific resolvers for certain object types directly, doing something like this:

const typeDefs = gql`
    type Query {
      getBook(bookId: ID!): BookPayload
    }

    type BookPayload {
        book: Book
        userErrors: UserError
    }

    type Book {
      id: ID!
      title: String
      author: String
    }
`;

const resolvers = {
    Query: {
        getBook: (parent, args, context, info) => {
            return {
                book: { id: args.bookId }
        }
    },
    Book: (parent) => {  // this object type level resolver doesn't seem to work
        return {
            id: parent.id,
            ...fetchBookMetadata(parent.id)
        };
    }
};

I understand this is a trivial example and might seem a bit over engineered, but it does make more sense (at least for us) when the schema starts becoming very complicated with hundreds cross references all over the place. Is there a good way to solve this right now?

like image 631
Jimmy C Avatar asked Dec 02 '25 22:12

Jimmy C


1 Answers

Yes, you should be able to do this or something very similar using directives, check this out:

https://www.apollographql.com/docs/graphql-tools/schema-directives.html#Fetching-data-from-a-REST-API

I will literally post the quote and the example from this article here.

Suppose you’ve defined an object type that corresponds to a REST resource, and you want to avoid implementing resolver functions for every field

const typeDefs = `
directive @rest(url: String) on FIELD_DEFINITION

type Query {
  people: [Person] @rest(url: "/api/v1/people")
}`;

class RestDirective extends SchemaDirectiveVisitor {
  public visitFieldDefinition(field) {
    const { url } = this.args;
    field.resolve = () => fetch(url);
  }
}

According to the spec, the GraphQL execution engine runs over selection sets which are broken down into individual fields. Every single field will be checked for either a value or an existing resolver.

It seems that if you define a directive such as the one above, you do not change this basic behaviour, but you do intercept and add an extra custom step to be executed before further resolution.

Perhaps something similar is possible with custom scalars, but this would not work well with schema design.

like image 108
Avius Avatar answered Dec 04 '25 12:12

Avius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!