GraphQLError: There can be only one fragment named

GraphQLError: There can be only one fragment named

在使用 graphql-react

构建的客户端应用程序上

graphQL 查询字符串由多个片段组成,如下所示:

const fragmentAddress = `
    fragment address on Address {
        id
        number
        street
        code
        city
    }
`

const fragmentOffice = `
    fragment office on Office {
        id
        address {
            ...address
        }
    }

    ${fragmentAddress}
`

const User = `
    query User($id: ID) {
        address {
            ...address
        }
        office {
            ...office
        }
    }

    ${fragmentAddress}
    ${fragmentOffice}
`

User returns 上的查询出现此错误:GraphQLError: There can be only one fragment named address

我看到graphql-tag有去重功能,但是不能返回一个字符串。

如何从 graphql 查询字符串中删除重复片段?

我只是found the answer:

使用 graphql-tag 进行去重复和 graphql/language/printer 转换回字符串:

import gql from 'graphql-tag'
import { print } from 'graphql/language/printer'

const fragmentAddress = gql`
    fragment address on Address {
        id
        number
        street
        code
        city
    }
`

const fragmentOffice = gql`
    fragment office on Office {
        id
        address {
            ...address
        }
    }

    ${fragmentAddress}
`

const User = gql`
    query User($id: ID) {
        address {
            ...address
        }
        office {
            ...office
        }
    }

    ${fragmentAddress}
    ${fragmentOffice}
`

const queryString = print(query)