繁体   English   中英

当没有数据返回时,GraphQL 变异返回类型应该是什么?

[英]What should be the GraphQL mutation return type when there is no data to return?

我有一个 Apollo GraphQL 服务器,我有一个删除记录的突变。 This mutation receives the UUID of the resource, calls a REST (Ruby on Rails) API and that API just returns an HTTP code of success and an empty body (204 No Content) when the deletion was successful and an HTTP error code with an error删除不起作用时的消息(404 或 500,典型的 REST 删除端点)。

在定义 GraphQL 突变时,我必须定义突变返回类型。 突变返回类型应该是什么?

input QueueInput {
  "The queue uuid"
  uuid: String!
}


deleteQueue(input: QueueInput!): ????????

我可以让它与几种不同类型的返回(布尔、字符串......)一起工作,但我想知道最佳实践是什么,因为我尝试过的返回类型都没有感觉正确。 我认为重要的是,在调用突变后,在客户端我有一些关于如果事情进展顺利(API 返回 204 不是内容)或发生错误(API 返回 404 或 500)会发生什么的信息,并且理想情况下有一些关于错误。

GraphQL 中的字段必须始终具有类型。 GraphQL 有null的概念,但 null 本身并不是一个类型——它只是代表缺乏价值。

GraphQL 中没有“void”类型。 但是,默认情况下,类型可以为空,因此无论字段的类型如何,您的解析器都不会返回任何内容,并且该字段将简单地解析为 null。 所以你可以

type Mutation {
  deleteQueue(input: QueueInput!): Boolean #or any other type
}

或者,如果您想要一个专门表示 null 的标量,您可以创建自己的.

const { GraphQLScalarType } = require('graphql')

const Void = new GraphQLScalarType({
  description: 'Void custom scalar',
  name: 'Void',
  parseLiteral: (ast) => null,
  parseValue: (value) => null,
  serialize: (value) => null,
})

然后做

type Mutation {
  deleteQueue(input: QueueInput!): Void
}

也就是说,通常的做法是返回一些东西 对于删除,通常返回已删除的项目或至少返回其 ID。 这有助于客户端的缓存管理。 返回某种突变有效负载类型以更好地封装客户端错误也变得越来越普遍。

您可以在“有效负载”类型中包含任意数量的字段,如下所示:

type Mutation {
  deleteQueue(input: QueueInput!): DeleteQueuePayload
}

type DeleteQueuePayload {
  # the id of the deleted queue
  queueId: ID

  # the queue itself
  queue: Queue

  # a status string
  status: String

  # or a status code
  status: Int

  # or even an enum
  status: Status

  # or just include the client error
  # with an appropriate code, internationalized message, etc.
  error: ClientError

  # or an array of errors, if you want to support validation, for example
  errors: [ClientError!]!
}

DeleteQueuePayload 甚至可以是不同类型的联合,使客户端能够使用__typename来确定突变的结果。

但是,您公开的信息取决于您的特定需求,而您采用的特定模式归结为意见。

有关其他讨论和示例,请参见此处此处

我将 graphql 服务器与 prisma 一起使用,并且在删除某些 prisma 时返回有关确实被删除的内容的信息。 这很好,因为当您从客户端执行删除并返回有关它的响应时,可以帮助您通过更新缓存来更改 ui

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM