I have a gql mutatation for hasura that both inserts and updates based on whether the $vendorLicenseId has been passed to id like so:
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:
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.
So in my API definition:
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
}
} `;