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

查看:59
本文介绍了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.

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

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天全站免登陆