动态 GraphQL 架构? [英] Dynamic GraphQL schema?

查看:25
本文介绍了动态 GraphQL 架构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要提交表单数据的变更,此数据可能因您填写的表单而异.

I have a mutation that is going to submit a form data, this data can vary depending by the form you are filling out.

表单会很多,它们将共享相同的步骤"(每个表单由 1 个或多个页面/步骤组成).

The forms are going to be a lot, and they will share the same "steps" (each form is composed by 1 or more pages/steps).

因此,我们可能有这些可重复使用的步骤:

So, we may have these reusable steps:

  • 最喜欢的水果
  • 出生日期
  • 姓名和姓氏

还有这两种形式:

  • 通用信息 (genericInfo):姓名 + 出生日期
  • 你吃什么?(whatYouEat):名字和姓氏 + 喜欢的水果
  • Generic info (genericInfo): Name and surname + Date of birth
  • What do you eat? (whatYouEat): Name and surname + Fav fruit

我需要一种方法来进行单个更改,它允许定义表单名称,并采用需要根据此类表单名称进行验证的 data 对象.

I'd need a way to have a single mutation, that allows to define the form name, and takes a data object that needs to be validated based on such form name.

例如,如果我称之为突变:

For instance, if I call this mutation:

submitForm(formName: $formName, formData: $formData) {
  resultMessage
}

formName 设置为 genericInfoformData 设置为 { nameAndSurname: 'Foo Bar', favFruit: 'apple' },它应该抛出一个错误,因为 genericInfo 不需要 favFruit,而是 dateOfBirth.

with formName set to genericInfo and formData set to { nameAndSurname: 'Foo Bar', favFruit: 'apple' }, it should throw an error because genericInfo doesn't expect favFruit, but dateOfBirth.

这可以用 GraphQL 实现吗?有没有更好的方法可以到达这里?

Can this be achieved with GraphQL? Are there better ways to get here maybe?

推荐答案

GraphQL 不直接允许这样做.输入对象类型具有固定结构,并且没有条件验证(内置;您的解析器函数可能会根据其自身的检查产生错误,而这些检查比模式中的内容更丰富).

GraphQL doesn’t directly allow this. Input object types have fixed structure, and there’s no conditional validation (built-in; your resolver function could produce errors based on its own checks that are richer than what’s in the schema).

我见过的最常见的模式采用 Relay GraphQL 突变约定(即使您不希望您的客户使用 Relay).每个可能的操作都有一个突变(在您的情况下,每个提交的表单有一个突变)和每个突变的不同输入对象类型.

The most common pattern I’ve seen adopts the Relay GraphQL mutation conventions (even if you don’t expect your clients to be using Relay). This has one mutation per possible action (in your case, one mutation per submitted form) and a distinct input object type per mutation.

另请注意,输入对象类型可以嵌套,因此在您的示例中,您可以编写

Also note that the input object types can be nested, so in your example, you could write

input Name {
  givenName: String!
  surname: String!
}

input Fruit {
  name: String!
}

input WhatYouEatInput {
  name: Name!
  fruit: Fruit!
}

mutation {
  whatYouEat(input: WhatYouEatInput!): WhatYouEatPayload!
}

这将允许跨不同的突变类型重用模式的公共部分.

which would allow reusing the common parts of the schema across different mutation types.

这篇关于动态 GraphQL 架构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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