简体   繁体   English

在 Javascript 中使用 GraphQL + Apollo 客户端查询具有部分字符串匹配的数据

[英]Query data with partial string match using GraphQL + Apollo client in Javascript

I have the following query:我有以下查询:

function useAllOrders(ownerId, storeId) {
  const { data, loading, error } = useQuery(
    gql`
      query getOrders($ownerId: String!) {
        orders(query: { owner_id: $ownerId }) {
          _id
          // ... field list              
        }
      }
    `,
    { variables: { ownerId: `owner_id=${ownerId}&store_id=${storeId}` } }
  );
  if (error) {
    throw new Error(`Failed to fetch tasks: ${error.message}`);
  }
  const orders = data?.orders ?? [];
  return { orders, loading };
}

What I need to do is being able to query the order just by owner if storeId is null|undefined.如果 storeId 为空|未定义,我需要做的是能够仅按所有者查询订单。 That means that I should be able to do a partial find with owner_id=${ownerId}%.这意味着我应该能够使用 owner_id=${ownerId}% 进行部分查找。 How can I achieve this?我怎样才能做到这一点?

Assuming ownerId variable is a composite variable (odd) then假设ownerId变量是一个复合变量(奇数),那么

{ variables: { ownerId: `owner_id=${ownerId}&store_id=${storeId}` } }

would become会成为

{ variables: { ownerId: `owner_id=${ownerId}${storeId ? `&store_id=${storeId}` : ''}` } }

You just need a conditional check when creating the variable's value.创建变量的值时,您只需要进行条件检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM