GraphQL Schema to handle mixed types

夙愿已清 提交于 2019-12-03 14:24:43

You either have to make these disparate types implement the same interface, make your resolvers return unions, or create a custom scalar to hold the dynamic data.

The cleanest approach is the first one: if your resulting objects can be of a limited number of types, define the types so that they implement the same interface, and type your resolvers by the interface. This allows the client to conditionally select sub-fields based on the actual type, and you maintain type safety.

The second approach has similar limitations: you need to know the possible types ahead of time, but they do not have to implement the same interface. It is preferable when the possible values are unrelated to each other and have either/or semantics, like success/failure.

The custom scalar approach is the only one in which you do not need to know the possible types of the result, i.e. the structure of the result can be completely dynamic. Here's an implementation of that approach, known as JSON scalar (i.e. cram any JSON-serializable structure into a scalar value). The big downside of this approach is that it makes sub-selection impossible, as the entire value becomes one big scalar (even though it's a complex object).

I think it's possible to make a custom/generic type that will fit the need. So that way it's still a strong typed array but the type will be flexable enough to set what you need.

Here is an example with custom types: https://github.com/stylesuxx/graphql-custom-types

If data is completely JSON and you would rather preserve them as is, check out JSON scalar type. Basically,

import { GraphQLObjectType } from 'graphql';
import GraphQLJSON from 'graphql-type-json';

export default new GraphQLObjectType({
  name: 'MyType',
  fields: {
    myField: { type: GraphQLJSON },
  },
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!