我有几个查询具有相同的返回类型:
// 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的新手,任何关于重构的建议都将不胜感激,谢谢。
可以使用片段(源1,源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}
`,