graphql - 将消息返回给用户的 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 件”,或者如果库存已用完,“此商品已无库存,请更新库存以继续”。
我怎样才能做到这一点?
解决方案
最好的方法是在您的前端部分检查计数,并且根本不允许用户添加超过库存单位,如果计数符合条件,您还需要检查您的后端,所以我建议使用一个复杂的功能,像这样:
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
}
推荐阅读
- azure-synapse - 如何使用 Azure Synapse Serverless SQL 池在 Azure Data Lake Gen2 中创建空白的“Delta”湖表架构?
- c# - ASP.NET MVC C# Google Drive API 重定向不匹配 URI
- python - 在python中动态访问列表项
- python - 如何使用我的 python 包发布我的单元测试
- node.js - 多个 URL(UI 页面和 API)的 Nginx 位置正则表达式?
- pandas - 了解 Pandas 系列数据结构
- android - 无法解决这个错误?Kotlin(二维码阅读器)
- python - MetPy 0.12->1.1 升级后从 THREDDS 服务器创建卫星图像时出错
- c++ - c++ 使用 condition_variable 作为产生线程的类的类成员
- c# - 出现错误“无法从 'double' 转换为 'System.ReadOnlySpan
" 分配变量时