0

我有几个具有相同返回类型的查询:

// Query 1
gql`
        mutation insert_shops_users($shopId: uuid) {
          insert_shops_users(objects: [{ shopId: $shopId }]) {
            affected_rows
            returning {
              Shop {
                id
                users {
                  userId
                }
              }
            }
          }
        }
      `,
// Query 2
gql`
        mutation delete_shops_users_by_pk($shopId: uuid!, $userId: String!) {
          delete_shops_users_by_pk(shopId: $shopId, userId: $userId) {
            Shop {
              id
              users {
                userId
              }
            }
          }
        }
      `,

现在,我想提取这部分,例如在名称下ShopUserResult并在两个查询中使用它:

在 ShopUserResult 下提取

Shop {
  id
  users {
    userId
  }
}

结果查询

// Query 1 - after refactor
gql`
        mutation insert_shops_users($shopId: uuid) {
          insert_shops_users(objects: [{ shopId: $shopId }]) {
            affected_rows
            returning {
             ShopUserResult
            }
          }
        }
      `,
// Query 2 - after refactor
gql`
        mutation delete_shops_users_by_pk($shopId: uuid!, $userId: String!) {
          delete_shops_users_by_pk(shopId: $shopId, userId: $userId) {
            ShopUserResult
          }
        }
      `,

我是graphql的新手,任何关于重构的建议都将不胜感激,谢谢。

4

1 回答 1

0

可以使用片段(source 1source 2)重构重复的字段集:

查询 - 之前

gql`
  mutation insert_shops_users($shopId: uuid) {
    insert_shops_users(objects: [{ shopId: $shopId }]) {
      affected_rows
      returning {
        Shop {
          id
          users {
            userId
          }
        }
      }
    }
  }
      `,

查询 - 使用片段后

分段
const ShopWithUsers = gql`
  fragment ShopWithUsers on shops {
    id
    users {
      userId
    }
  }
`
询问
gql: gql`
  mutation insert_shops_users($shopId: uuid) {
    insert_shops_users(objects: [{ shopId: $shopId }]) {
      affected_rows
      returning {
        Shop {
          ...ShopWithUsers
        }
      }
    }
  }
  ${ShopWithUsers}
`,
于 2020-07-10T06:09:01.593 回答