处理混合类型的 GraphQL 模式 [英] GraphQL Schema to handle mixed types

查看:18
本文介绍了处理混合类型的 GraphQL 模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始研究使用 GraphQL 请求动态数据配置的可能性.我首先想到的是 GraphQL 的强类型概念.

I've recently started to research the possibility of using GraphQL for requesting dynamic data configurations. The very first thing that jumps out at me is the strongly-typed concept of GraphQL.

GraphQL 模式有没有办法处理混合类型对象的数组?我将不胜感激,无论是解释还是可能的参考资料,我都可以阅读.

Is there a way for GraphQL schemas to handle arrays of mixed type objects? I would greatly appreciate either an explanation or possibly a reference I can read over.

我目前正在使用带有 Node.js 的 GraphQL,但以后的实现将不在 Java 容器中.所有数据都将从 MongoDB 中提取 JSON.

I am currently working with GraphQL with Node.js but a later implementation will be out of a Java Container. All data will be JSON pulled from MongoDB.

推荐答案

你要么必须让这些不同的类型实现相同的接口,让你的解析器返回联合,或者创建一个自定义标量来保存动态数据.

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.

第二种方法有类似的限制:您需要提前知道可能的类型,但它们不必实现相同的接口.当可能的值彼此不相关并且具有either/or语义(如成功/失败)时,这是更可取的.

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.

自定义标量方法是唯一一种不需要知道结果可能类型的方法,即结果的结构可以是完全动态的.这是该方法的实现,称为 JSON 标量(即将任何 JSON 可序列化结构填充为标量值).这种方法的最大缺点是它使子选择变得不可能,因为整个值变成了一个大标量(即使它是一个复杂的对象).

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).

这篇关于处理混合类型的 GraphQL 模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆