[英]Use template literals with conditional logic in hasura GQL mutation
I have a gql mutatation for hasura that both inserts and updates based on whether the $vendorLicenseId has been passed to id like so:我有一个 hasura 的 gql 突变,它根据 $vendorLicenseId 是否已传递给 id 来插入和更新,如下所示:
export const UPDATE_LICENSE = gql`
mutation UpdateLicense(
$vendorId: Int!
$licenseId: Int!
$vendorLicenseId: Int
) {
insert_license_one(
object: {
id: $vendorLicenseId:
vendor_id: $vendorId
license_id: $licenseId
}
on_conflict: {
constraint: license_pkey
update_columns: [
license_number
license_id
]
}
) {
id
license_id
vendor_id
license_number
}
}
`;
The problem is, it's non nullable and if I just leave it like the rest of the variables, like above and don't pass the vendorLicenseId, it passes to hasura as null (obviously) and fails:问题是,它是不可空的,如果我像上面的变量 rest 那样保留它并且不传递 vendorLicenseId,它会作为 null 传递给 hasura(显然)并失败:
Is there a way to check in the mutation for the variable to exist and if it doesn't just omit the entire line?有没有办法检查变量是否存在的突变,以及它是否不只是省略整行?
something like this:是这样的:
export const UPDATE_LICENSE = gql`
mutation UpdateLicense(
$vendorId: Int!
$licenseId: Int!
$vendorLicenseId: Int
) {
insert_license_one(
object: {
${ $vendorLicenseId ? `id: $vendorLicenseId`: ``}
vendor_id: $vendorId
license_id: $licenseId
}
on_conflict: {
constraint: license_pkey
update_columns: [
license_number
license_id
]
}
) {
id
license_id
vendor_id
license_number
}
}
`;
I've tried variations of this and can't get it to work.我试过这个的变体,但无法让它工作。 Is there a right way or better way to do this?
有没有正确的方法或更好的方法来做到这一点?
Here's what I did to fix this.这是我为解决此问题所做的工作。
Instead of trying to insert logic inside the string with template literals, I instead intercepted the variables earlier, added in conditions, and then passed the entire object.我没有尝试使用模板文字在字符串中插入逻辑,而是更早地拦截了变量,添加了条件,然后传递了整个 object。
So in my API definition:所以在我的 API 定义中:
export const updateLicense = async ({
userId,
licenseId,
vendorLicenseId
dispatch,
getState,
}: licenseUpdateParams & BaseAPIRequest) => {
const licenseVars: any = {
user_id: userId,
license_id: licenseId,
};
// it's non-nullable in hasura, but we need to omit it for insert so only pass it in if exists
if (licenseId) licenseVars.id = vendorLicenseId;
return await SIGraphQL.graphqlRequest({
gql: UPDATE_LICENSE,
variables: {
licenseVars,
},
getState,
dispatch,
});
};
export const UPDATE_LICENSE = gql`
mutation UpdateLicense( $licenseVars: license_insert_input!) {
insert_license_one(
object: $licenseVars
on_conflict: {
constraint: license_pkey
update_columns: [
license_number
license_id
]
}
) {
id
license_id
user_id
license_number
}
} `; }`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.