I saw this question which is very close to what I'm trying to accomplish, but it didn't quite work for me because the endpoint is a graphQL endpoint and there's another nested property by the name of the query. For example, if my query is:
const query = `query Query($age: Int!){
users(age: $age) {
name
birthday
}
}`;
Then the fetched object from the above linked answer is data.data.users
, where the last property comes from the graphql query name itself. I was able to modify the code from the above link to the following:
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>);
}
...which works when I'm only providing a single query to the graphQL endpoint. How could I generalize so that it would work for whatever number of queries? For example, what if I know my query will return User[]
and Post[]
, as a tuple, due to the following graphql query:
const query = `query Query($age: Int!, $username: String!){
users(age: $age) {
name
birthday
}
posts(username: $username) {
date
}
}`;
}
Then I would like something like the following to work:
const myData = graphQLFetch<[User[], Post[]]>(url, query, variables);
Is something like this possible?