GraphQL 中的字段必须始终具有类型。 GraphQL 有null 的概念,但 null 本身并不是一个类型——它只是表示缺乏价值。
GraphQL 中没有“void”类型。但是,默认情况下类型可以为空,因此无论字段的类型如何,您的解析器都不会返回任何内容,并且该字段将简单地解析为 null。所以你可以做
type Mutation {
deleteQueue(input: QueueInput!): Boolean #or any other type
}
或者如果你想要一个专门表示null的标量,你可以create your own。
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
}
也就是说,通常的做法是返回 something。对于删除,通常返回已删除的项目或至少返回其 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 来确定突变的结果。
但是,您公开哪些信息取决于您的具体需求,而您采用的具体模式归结为意见。
有关更多讨论和示例,请参阅 here 和 here。