graphql - 可选参数 - 突变 - TypeGraphQL
问题描述
我想更新一个实体的firstName
and 。lastName
profile
我希望用户能够同时更新它们或仅更新其中之一。
但是我不知道如何进行突变,以使参数 (firstName
和lastName
) 之一是可选的。
我当前的代码 如果用户同时输入firstName
和lastName
@Mutation(() => Boolean)
@UseMiddleware(isAuth)
async updateProfile(
@Ctx() {payload}: MyContext,
@Arg('firstName') firstName: string,
@Arg('lastName') lastName: string,
) {
try {
const profile = await Profile.findOne({where: { user: payload!.userId}})
if (profile) {
profile.firstName = firstName
profile.lastName = lastName
await profile.save();
return true
}
return false
} catch(err) {
return false
}
}
如果我运行突变(不包括一个参数):
mutation{
updateProfile(firstName: "test")
}
我得到错误:
"message": "String!" 类型的字段 "updateProfile" 参数 "lastName" 是必需的,但未提供。
我在想一种解决方法可能是在中传递一个默认参数,@Arg
但后来我意识到默认参数是静态的,而不是动态的,所以我不能为那个特定的配置文件传递firstName
orlastName
解决方案
要使参数成为可选参数,请将第二个参数传递给@Arg
装饰,如下所示:
@Arg('firstName', { nullable: true }) firstName: string,
@Arg('lastName', { nullable: true }) lastName: string,
在 GraphQL 中,参数要么是必需的,要么不是。无法指定“只需要其中一个参数”。如果您需要这种验证逻辑,则需要在解析器中自己实现它。
推荐阅读
- javascript - javascript中的curl -u请求
- c# - 在 C# 中使用 linq 查询比较两个字典键
- wordpress - 木材是否有像 404 一样的默认 500 模板?
- amazon-web-services - 已删除 AWS CodeBuild 分支过滤器选项
- c# - 检查对象列表是否包含特定值
- asp.net - 路由 IIS - Angular - Asp.Net Core
- mayavi - 如何修复 Mayavi contour3d?
- go - 我需要在 XORM 中关闭 sqlite3 数据库连接吗?
- php - 下一个按钮在代码 php 的按钮中不起作用
- python - 为什么 os.system 会阻止程序执行?