我想更新firstName和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":"Field "updateProfile“参数”参数"lastName“类型为"String!”是必需的,但没有提供。
我在想解决办法可能是在@Arg中传递一个默认参数,但后来我意识到默认参数是静态的,而不是动态的,所以我不能为该特定的配置文件传递firstName或lastName。
发布于 2020-08-07 00:11:48
若要使参数可选,请向@Arg装饰传递第二个参数,如下所示:
@Arg('firstName', { nullable: true }) firstName: string,
@Arg('lastName', { nullable: true }) lastName: string,在GraphQL中,参数要么是必需的要么是不需要的。没有办法具体说明“只需要其中一个参数”。如果您需要这种验证逻辑,则需要在解析器中自己实现它。
https://stackoverflow.com/questions/63293280
复制相似问题