I came across a similar question that almost solved my issue, but it didn't quite work for me because the endpoint I'm using is a graphQL endpoint with an additional nested property called query. For instance, if my query looks like this:
const query = `query Query($age: Int!){
users(age: $age) {
name
birthday
}
}`;
Then according to the solution in the linked answer, the fetched object would be data.data.users
, where the last property corresponds to the name of the graphql query itself. I tweaked the code from the link to this:
function graphQLFetch<T>(url: string, query: string, variables = {}): Promise<T> {
return fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables }),
}).then((response) => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then((responseJson) => responseJson.data[Object.keys(responseJson.data)[0]] as Promise<T>);
}
...and it works perfectly when sending a single query to the graphQL endpoint. But how can I make it more versatile so it can handle any number of queries? For example, what if I know my query will return User[]
and Post[]
as a tuple, based on the following graphql query:
const query = `query Query($age: Int!, $username: String!){
users(age: $age) {
name
birthday
}
posts(username: $username) {
date
}
}`;
}
In that case, I'd like something like this to function correctly:
const myData = graphQLFetch<[User[], Post[]]>(url, query, variables);
Do you think achieving this level of flexibility is feasible?