GraphQLError: There can be only one fragment named

Viewed 1587

On a client app built with graphql-react,

graphQL query strings are made of multiple fragments like so:

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

A query on User returns this error: GraphQLError: There can be only one fragment named address.

I saw that graphql-tag has a dedup fonction, but it can't give a string back.

How is it possible to deduplicate fragments from a graphql query string?

1 Answers

I just found the answer:

use graphql-tag for dedpulication and graphql/language/printer to convert back to a string:

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)
Related