【问题标题】:Custom condition for GraphQL mutation that returns message to user将消息返回给用户的 GraphQL 突变的自定义条件
【发布时间】:2021-08-11 13:26:39
【问题描述】:

当用户尝试将新商品添加到不再有库存的订单时,为用户创建响应的最佳方式是什么? 这是我的简化设置:

type Product {
    id: ID!
    unitsInStock: Int!
}

type OrderItem {
    id: ID!
    units: Int!
    product: Product! @belongsTo
}

type Mutation {
    createOrderItem(input: CreateOrderItemInput! @spread): OrderItem @create
}

input ProductBelongsTo {
    connect: ID
    create: CreateOrderItemInput
}

input CreateOrderItemInput {
    units: Int!
    product: ProductBelongsTo
}

基本上,在提交createOrderItem 突变之前,我想检查为订单选择的产品是否有库存,例如,如果用户选择了太多单位的产品,他会收到一条友好的消息,说“只有还剩 10 件”,或者如果库存已用完“此商品已无库存,请更新库存以继续”。

我该怎么做?

【问题讨论】:

  • 在 LH 文档中搜索“错误处理”!?
  • 我可以通过错误来做到这一点,但错误通常是针对出错的事情并且它不能正确填写。
  • 您的突变只能返回或不返回...返回错误 - 基于 API 类型。如何在 FE 上解释此错误消息取决于您,它可以显示为漂亮、友好的消息;)
  • 我了解如何使用自定义异常和自定义突变来做到这一点。但想知道是否有更好的方法或标准的方法。因为它感觉更像是一个 hack,而不是一个适当的解决方案。
  • 如何使用自定义验证规则使其工作?甚至可以与validator class 结合使用以使其很好地捆绑在一起。我认为这就是没有自定义突变解析器的情况。

标签: graphql laravel-lighthouse


【解决方案1】:

最好的方法是在您的前端部分检查计数,根本不允许用户添加超过库存单位,如果计数符合条件,您还需要检查您的后端,所以我建议使用一个复杂的函数,像这样:

createOrderItem(input: CreateOrderItemInput! @spread): OrderItem
@field(resolver: "App\\GraphQL\\OrderItemComplex@create")

App\GraphQL\OrderItemComplex 看起来像这样:

public function create($rootValue, array $args)
{
    // simply check the count before creating any record and
    // throw an error with the appropriate message if sth is wrong
}

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 2020-09-21
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    相关资源
    最近更新 更多