graphql-tag icon indicating copy to clipboard operation
graphql-tag copied to clipboard

Build dynamic query, got 'Syntax Error: Expected Name, found }'

Open race604 opened this issue 5 years ago • 4 comments

I want to create a dynamic query based on different inputs

export function generateBatchQuery(names: string[]) {
  const subqueries = names.map(name => (
    `
      ${name}: getConfig(request: {
        name: "${name}"
      }) {
        ...configFeilds
      }
    `
  )).join('\n');

  return gql`
  query BatchGetConfigs {
      ${subqueries}
  }
  ${configFragment}
  `;
}

I am pretty sure the formatted string for graphql query is correct, but graphql-tag always claim error when build:

error { GraphQLError: Syntax Error: Expected Name, found }
    at syntaxError (/Users/xxxx/node_modules/graphql/error/syntaxError.js:15:10)
    at expectToken (/Users/xxxx/node_modules/graphql/language/parser.js:1428:38)
    at parseName (/Users/xxxx/node_modules/graphql/language/parser.js:91:15)
    at parseField (/Users/xxxx/node_modules/graphql/language/parser.js:306:21)
    at parseSelection (/Users/xxxx/node_modules/graphql/language/parser.js:295:76)
    at many (/Users/xxxx/node_modules/graphql/language/parser.js:1515:16)
    at parseSelectionSet (/Users/xxxx/node_modules/graphql/language/parser.js:282:17)
    at parseField (/Users/xxxx/node_modules/graphql/language/parser.js:323:63)
    at parseSelection (/Users/xxxx/node_modules/graphql/language/parser.js:295:76)
    at many (/Users/xxxx/node_modules/graphql/language/parser.js:1515:16)
  message: 'Syntax Error: Expected Name, found }',
  locations: [ { line: 4, column: 3 } ] }

From this error, I known that the parser always expect static names in query body, but in my situation, I want dynamically build the query. How can I walk around this?

race604 avatar Aug 02 '19 17:08 race604

I just realize that we should not use graphql-tag for dynamic query, right? I can use import { parse } from 'graphql' to parse query in this situation:

return parse(`
  query BatchGetConfigs {
      ${subqueries}
  }
  ${configFragment}
  `);

race604 avatar Aug 03 '19 08:08 race604

I have the same problem and the example in the apollo docs uses graphql-tag https://www.apollographql.com/docs/react/v2.5/advanced/fragments/#reusing-fragments

geiszla avatar Feb 16 '20 17:02 geiszla

@geiszla I think their example works because the expanded variable is already a gql tag, not a string. The problem comes when you're trying to expand string variables inside gql tags.

digeomel avatar Feb 18 '20 10:02 digeomel

@digeomel ✅ I had the error but it went away as soon as i remove the expanded strings

fibonacid avatar Jul 04 '20 14:07 fibonacid