可选参数 - 突变 - TypeGraphQL
Optional argument - Mutation - TypeGraphQL
我想更新 profile
实体的 firstName
和 lastName
。
我希望用户能够同时更新它们或只更新其中之一。
但是我不知道如何进行突变以使参数(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" argument "lastName" of type "String!" is required, but it was not provided.
我在想解决方法是在 @Arg
中传递默认参数,但后来我意识到默认参数是静态的,而不是动态的,所以我无法传递 firstName
或 lastName
对于该特定配置文件
要使参数可选,请将第二个参数传递给 @Arg
装饰器,如下所示:
@Arg('firstName', { nullable: true }) firstName: string,
@Arg('lastName', { nullable: true }) lastName: string,
在 GraphQL 中,参数要么是必需的,要么不是。无法指定“仅需要这些参数之一”。如果您需要那种验证逻辑,您需要自己在解析器中实现它。
我想更新 profile
实体的 firstName
和 lastName
。
我希望用户能够同时更新它们或只更新其中之一。
但是我不知道如何进行突变以使参数(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" argument "lastName" of type "String!" is required, but it was not provided.
我在想解决方法是在 @Arg
中传递默认参数,但后来我意识到默认参数是静态的,而不是动态的,所以我无法传递 firstName
或 lastName
对于该特定配置文件
要使参数可选,请将第二个参数传递给 @Arg
装饰器,如下所示:
@Arg('firstName', { nullable: true }) firstName: string,
@Arg('lastName', { nullable: true }) lastName: string,
在 GraphQL 中,参数要么是必需的,要么不是。无法指定“仅需要这些参数之一”。如果您需要那种验证逻辑,您需要自己在解析器中实现它。