Is it possible to construct gql string variables with passed variables as such?:
getRules(model: string){
var queryVar = gql`
query HyperionSchemaQuery {
rules {
`+model+` {
rules
}
}
}
`;
var rulesArray;
this.apollo.watchQuery({
query: queryVar
}).subscribe(({data}) => {
rulesArray = JSON.parse(data.rules[model].rules);
console.log(rulesArray);
});
}
this.getRules("Day"); gives error:
EXCEPTION: Error in ./ProjectMain class ProjectMain - inline template:191:108 caused by: Syntax Error GraphQL (4:7) Expected Name, found EOF
3: rules {
4:
^
A multiline string variable, without the "gql" logs the following:
var queryVar = `
query HyperionSchemaQuery {
rules {
`+model+` {
rules
}
}
}
`;
logs:
query HyperionSchemaQuery {
rules {
Day {
rules
}
}
}
Which would be how an accepted graphql-query would look like in my case. Is there some way I could construct such a variable and pass it as the query in my watchQuery()? Iv'e tested in many different ways (to construct the gql`` string) without success and can't find anything in the documentation or in the GitHunt example.
First of all, this won't work:
gql`
query HyperionSchemaQuery {
rules {
`+model+` {
rules
}
}
}
`;
gql is a function, by using it like this:
gql`some string`
TS or Babel compiler turns this into
gql(['some string'])
You decoupled the string to 3 different strings, so you have:
gql`query...` + model + `rest of the query`
So you're using gql only in the first string (query...)
this should work
gql`
query HyperionSchemaQuery {
rules {
${model} {
rules
}
}
}
`;
This solved my problem.
This way I can get rules for every component in my app through one method in one single shared service B-)
Couldn't just figure out how to achieve this.
Thank you very much @kamilkisiela !
@patriknil90 Feel free to hit me with any question, any time :)
@patriknil90 I just want to warn you that this is not a good way of using GraphQL, see here: https://dev-blog.apollodata.com/5-benefits-of-static-graphql-queries-b7fa90b0b69a
@patriknil90 Do you think you could provide your full code for what worked here? Or perhaps you've found another way of doing this over the past year? I'm sure it's been a while so I understand if you can't find it. Thanks @patriknil90
@KevinDanikowski Sure!
getRulesFromServer(modelArray){
let getRulesQuery = this.constructRulesQuery(modelArray, "getRulesQuery")
return this.apollo.watchQuery({
query: getRulesQuery
});
}
constructRulesQuery(modelArray, queryName){
let rulesQueryString: string = "query " + queryName + " { rules { ";
for(let model in modelArray){
rulesQueryString += (modelArray[model] + " { rules } ")
}
rulesQueryString += "}}";
let rulesQuery = gql`
${rulesQueryString}
`;
return rulesQuery;
}
Most helpful comment
this should work