'Regular expression to get variables in Graphql query
I have a graphql query that I'd like to get the variable names and types. I'm using Apollo Client to handle my queries but I believe doesn't provide something to get variables names. Is there any API or library given that information?
Query example:
query Integrations($count: Int, $isAdmin: Boolean, $services: String) {
repository(uri: "$count: Int, $isAdmin: Boolean, $services: String") {
integrations(
filter: { limit: $count, ignoreCase: $isAdmin, id: $services }
) {
id
}
}
}
I'd like to receive an object like:
{
"count": "Int",
"isAdmin": "Boolean",
"services": "String"
}
Please note that this case could be handle by a regular expression, like this one:
[^"$\s]*\$([a-zA-Z0-9]*):\s*(String|Int|Float|Boolean)[^"$\s]*
Unfortunately, also match the variables inside a string (line 2)
Any idea?
Solution 1:[1]
Is there any API or library given that information?
Yes. Apollo Client uses graphql-tag which generates an AST of the query using the official graphql-js parser.
You should find the variable names and types using this same API:
import { parse, print, getOperationAST } from 'graphql';
const document = parse('…');
// const query = document.definitions.find(def => def.operation == "query" && def.name.value == 'Integrations');
const query = getOperationAST(document, 'Integrations');
for (const varDef of query.variableDefinitions) {
console.log(`Variable '${varDef.name.value}' has type ${print(varDef.type)}.`);
}
Don't use an ad-hoc regular expression.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
