【问题标题】:Use template literals with conditional logic in hasura GQL mutation在 hasura GQL 突变中使用具有条件逻辑的模板文字
【发布时间】:2022-06-10 23:05:25
【问题描述】:

我有一个针对 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
    }
  }
    `;

问题是,它是不可为空的,如果我像上面的其他变量一样保留它,并且不传递 vendorLicenseId,它会作为 null 传递给 hasura(显然)并且失败:

有没有办法检查变量是否存在的突变,如果它不只是省略整行?

类似这样的:

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
    }
  }
    `;

我已经尝试过这种方法的变体,但无法让它发挥作用。有没有正确的方法或更好的方法来做到这一点?

【问题讨论】:

  • 在将查询字符串传递给gql 辅助函数之前,您是否尝试过将查询字符串构造为常规的 const 字符串变量?

标签: javascript hasura gql


【解决方案1】:

这是我为解决此问题所做的。

我没有尝试使用模板字面量在字符串中插入逻辑,而是提前截取变量,添加条件,然后传递整个对象。

所以在我的 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
}

} `;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 2018-08-22
    相关资源
    最近更新 更多