atulmy/gql-query-builder

How to add a field with arguments but with no inner fields to the GraphQL Query?

MurzNN opened this issue · 1 comments

I'm working with Commercetools API, here is the reference https://docs.commercetools.com/api/graphql
And it requires to add fields with arguments, here is an example:

query MyQuery {
  product(sku: "SKU1") {
    id
    masterData {
      current {
        name(locale: "en")
      }
    }
  }
}

The required fragment is slug(locale: "en") and I can't find a way to make it using the gql-query-builder library.
If I use the operation without fields like this:

const query = gql.query({
  operation: 'MyQuery',
  fields: [
    'id',
    {
      masterdata: [
        {
          current: [
            {
              operation: 'name',
              variables: { locale: "en" }
            },
          ]
        }
      ]
    }
  ]
})

console.log(query)

it produces an error:

node_modules/gql-query-builder/build/Utils.js:39
                .map(function (field) {
                 ^

TypeError: fields.map is not a function

Could you please give an example of how to build this query using the library? Thanks!

I found two workarounds for this:

  • First:
const query = gql.query({
  operation: 'MyQuery',
  fields: [
    'id',
    {
      masterdata: [
        {
          current: [
            {
              operation: 'name',
              fields: [],
              variables: { locale: "en" }
            },
          ]
        }
      ]
    }
  ]
})

It produces almost what I need, but extracts the value to variables, instead of keeping it inline:

{
  query: 'query ($locale: String) { MyQuery  { id, masterdata { current { name (locale: $locale)  } } } }',
  variables: { locale: 'en' }
}
  • Second:
const query = gql.query({
  operation: 'MyQuery',
  fields: [
    'id',
    {
      masterdata: [
        {
          current: [
            'name(locale: "en")',
          ]
        }
      ]
    }
  ]
})

It produces the correct result:

{
  query: 'query  { MyQuery  { id, masterdata { current { name(locale: "en") } } } }',
  variables: {}
}

but the problem is that I have to pass the arguments as the field name, that's no good.

So, if a correct solution for this task or better workarounds are present - please share!