graphql-tag
graphql-tag copied to clipboard
Build dynamic query, got 'Syntax Error: Expected Name, found }'
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?
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}
`);
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 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 ✅ I had the error but it went away as soon as i remove the expanded strings