首页 > 解决方案 > 将消息返回给用户的 GraphQL 突变的自定义条件

问题描述

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

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 件”,或者如果库存已用完,“此商品已无库存,请更新库存以继续”。

我怎样才能做到这一点?

标签: graphqllaravel-lighthouse

解决方案


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

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
}

推荐阅读