Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In GraphQL, how to handle the `resolveType` and `isTypeOf` when use the `interfaces` feature a lot?

I had read through this great gist - GraphQLInterfaceType

But still have some confusions:

  1. Is that really necessary to define ES6 classes for all GraphQL schema types?
    • Main concern here is: we will end up with lots of empty ES6 classes and equivalent amount of GraphQL types.
  2. If it is not, then how to handle the resolveType and isTypeOf properly when use the interfaces features a lot?
  3. Even I defined all the ES6 classes for all the GraphQL types, but the raw data are constructed in different place with different tech like grpc+protobuf, which has no any relation to these classes definitions, so how does the isTypeOf: (value) => value instanceof Dog work here?
like image 687
lnshi Avatar asked Apr 18 '17 10:04

lnshi


1 Answers

The implementation of resolveType and isTypeOf is very flexible for a reason: it's extremely application-specific. It depends on the database, the data models, how similar the types are, and so on. Some backends might have separate ES6 classes for all their models, especially if using an ORM, where it creates instances of those classes when you query the database. But an ORM is not necessary. And you shouldn't be required to instantiate any other classes to figure out the GraphQL type.

In some cases, you can determine the type solely from the properties on the objects. If this isn't the case for your app, there are things you can do to give hints. Here is a SQL example.

SELECT
  id,
  body,
  author_id,
  post_id,
  'Comment' AS "$type" -- leave a hint to resolve the type
FROM comments
UNION
SELECT
  id,
  body,
  author_id,
  NULL AS post_id,
  'Post' AS "$type" -- leave a hint to resolve the type
FROM posts

This query provides a "type hint", an additional computed column, so that implementing resolveType is a simple property lookup. Other DBMS can use a similar strategy.

like image 173
Andy Carlson Avatar answered Oct 26 '22 05:10

Andy Carlson