I've searched around for ways to query a graphQl endpoint, but so far they've all had a pretty similar and clunky solution as I have: string building. Here's a few links:
Ultimately, the code I'm running right now (and do not truly like) is:
// replace anything that looks like this => %someVar
// with the value at vars[someVar]
function injectVars(query, vars) {
return query.replace(/%([\d\w]+)/g, (_, varName) => {
if (!vars.hasOwnProperty(varName)) {
throw new Error(`Undefined variable: ${varName}`);
}
return vars[varName];
});
}
// a query with the injection point "%userId"
const userQuery = `query getUser{
user(
id: "%userId"
) {
id
name
}
}`;
// successful injection
const query = injectVars(userQuery, {
userId: "some-id-123"
});
console.log(query);
// failed usage
const willFail = injectVars(userQuery, {
nonVar: "missingUserId"
});
Problems I have with the code above:
Appears to be open to injection attacks
Not great type checking
Kind of a hassle with ENUMS, or type conversion (ie, take a date and make it string)
Not very extensible. Would have to copy paste the same stuff a lot for different iterations.
I'm new to this, and inherently don't trust my solutions yet.
Anyways, how do I query a GraphQl endpoint from node js without clunky string manipulation? Are there any tools/suggestions which would make this interaction more object oriented?
Use variables as shown in the official tutorial.
A GraphQL query can be parameterized with variables, maximizing query reuse, and avoiding costly string building in clients at runtime... Variables must be defined at the top of an operation and are in scope throughout the execution of that operation.
An example:
const query = `query getUser($id: ID!) {
user(
id: $id
) {
id
name
}
}`
const variables = {
id: 'someId'
}
fetch('/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query,
variables,
})
})
The JSON values you provide are parsed into the types you specify in your document (in the above example, an ID scalar). The variables will be validated by the GraphQL service so you could also skip checking if they are defined or the correct type. String values will be parsed into the appropriate enum value as long as the variable is declared as an enum type. IDs can be either Intergers or Strings. Input object types will be parsed and handled appropriately as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With