composing queries in Apollo Client - graphql

i'm learning to use apollo client and I saw that it used to contain "compose" method which combines multiple queries, so we can call two queries in a single request without explicitly write a whole new query.
lets say I have 2 queries
const getUsersQuery = gql`query getUsers ($name:String!){
users{
name
}
}`
const getPokemonsQuery = gql`query getPokemon($id:ID!){
pokemon (id:$id) {
name
}
}`
So a compose method will return an object which I can use to fetch these two queries in single request and include the variables for the two queries.
I didn't find a way to do it in the latest version.

Related

Is it possible to build GraphQL query where the second part of the query depends on the result of the first one?

I have a setup where I run a query on the frontend through the router (Apollo Federation Gateway) to two separate services exposing GQL endpoints - serviceA has findItems and serviceB has parseName.
Now I want to run the following query in one go:
query findMyItemDescriptionNameAndParse {
findItems(id: 1) {
description {
name
}
}
parseName(input: $name) {
parsedName {
name
}
}
}
Can Apollo pass the variables internally or I just have to split the query into two for such case?
Thank you.
Short answer: no. You'd have to run the two queries in sequence. What's preferable however is to define a different query that returns both the name and parsedName that you're looking for. Even better would be to extend the description to include a parsedName field and just write a resolver for that then you'd never need to run sequential queries.

Sending dynamic number of mutations at once

Is there a standard way to send a dynamic number of mutations in the same request with Apollo client ?
I have to deal with a Graphql API that only expose a single delete mutation, and I'd like to call it with multiple ids. Here's how it's defined:
mutation DeleteItemById($id: Int) {
delete_item(id: $id) {
id
}
}
From what I read, I could do something like
mutation DeleteItemById($id_1: Int, $id_2: Int) {
delete_item_1: delete_item(id: $id_1) {
id
}
delete_item_2: delete_item(id: $id_2) {
id
}
}
But how could I generate such a query dynamically ? Is it a good practice anyway ? I always read it was not a good idea to dynamically generate graphql queries.
Plus, I'm using graphql-codegen and statically defining queries in .graphql files, so I imagine it will have trouble parsing dynamic ones.
In general it's a bad idea to generate GraphQL queries dynamically. A good way to deal with this is to create a new mutation that supports multiple ids, validate and delete all in the same batch, like:
type Mutation {
deleteItems(ids: [String!]!): Boolean!
}

Call the same GraphQL mutation action many times in one http request [duplicate]

I have a mutation:
const createSomethingMutation = gql`
mutation($data: SomethingCreateInput!) {
createSomething(data: $data) {
something {
id
name
}
}
}
`;
How do I create many Somethings in one request? Do I need to create a new Mutation on my GraphQL server like this:
mutation {
addManySomethings(data: [SomethingCreateInput]): [Something]
}
Or is there a way to use the one existing createSomethingMutation from Apollo Client multiple times with different arguments in one request?
You can in fact do this using aliases, and separate variables for each alias:
const createSomethingMutation = gql`
mutation($dataA: SomethingCreateInput!) {
createA: createSomething(data: $dataA) {
something {
id
name
}
}
createB: createSomething(data: $dataB) {
something {
id
name
}
}
}
`;
You can see more examples of aliases in the spec.
Then you just need to provide a variables object with two properties -- dataA and dataB. Things can get pretty messy if you need the number of mutations to be dynamic, though. Generally, in cases like this it's probably easier (and more efficient) to just expose a single mutation to handle creating/updating one or more instances of a model.
If you're trying to reduce the number of network requests from the client to server, you could also look into query batching.
It's not possible so easily.
Because the mutation has one consistent name and graphql will not allow to have the same operation multiple times in one query. So for this to work Apollo would have to map the mutations into aliases and then even map the variables data into some unknown iterable form, which i highly doubt it does.

Passing Apollo Client cache data with apollo Query

I have two queries:
const GET_FILTERS = gql`
query getFilters {
filters #client {
id
title
selected
}
}
`
And
const GET_POSTS = gql`
query getPosts {
posts {
id
author
status
}
}
`
First one fetches the data from a local state using apollo-link-state and the second one is a external call.
I have a HOC for fetching posts setup like this:
const withPosts = (Component) => (props) => (
<Query
query={GET_POSTS}
>
{({loading, data, error})} => {
if(loading) return null
if(error) return null
return <Component {...data} {...props}/>
}}
</Query>
)
The fetching of the posts is fine but what I would like to do is to add whatever is returned from GET_FILTERS query with every call to GET_POSTS query?
One thing I could do is to wrap withPost in to another, lets say withFilters HOC, and pass the result in to GET_POSTS query as variables but I have been wondering if there is any other way to access that data via some sort of context and for example cache.readQuery using only withPost HOC.
Apollo has 'native' tools for HOC pattern, you can compose many (named) queries and mutations to enhance component. IMHO it's much more readable and powerfull than using query/mutaions components.
You can pass queried (filter) values as variables via data.fetchMore - of course you can use query component for 'inner query'.
Using cache directly isn't required while query 'cache-first' fetchPolicy option can be used.

Can graphql return aggregate counts?

Graphql is great and I've started using it in my app. I have a page that displays summary information and I need graphql to return aggregate counts? Can this be done?
You would define a new GraphQL type that is an object that contains a list and a number. The number would be defined by a resolver function.
On your GraphQL server you can define the resolver function and as part of that, you would have to write the code that performs whatever calculations and queries are necessary to get the aggregate counts.
This is similar to how you would write an object serializer for a REST API or a custom REST API endpoint that runs whatever database queries are needed to calculate the aggregate counts.
GraphQL's strength is that it gives the frontend more power in determining what data specifically is returned. Some of what you write in GraphQL will be the same as what you would write for a REST API.
There's no automatic aggregate function in GraphQL itself.
You can add a field called summary, and in the resolve function calculate the totals.
You should define a Type of aggregated data in Graphql and a function you want to implement it. For example, if you want to write the following query:
SELECT age, sum(score) from student group by age;
You should define the data type that you want to return:
type StudentScoreByAge{
age: Int
sumOfScore: Float
}
and a Graphql function:
getStudentScoreByAge : [StudentScoreByAge]
async function(){
const res = await client.query("SELECT age, sum(score) as sumOfScore
from Student group by age");
return res.rows;
}
... need graphql to return aggregate counts? Can this be done?
Yes, it can be done.
Does GraphQL does it automatically for you? No, because it does not know / care about where you get your data source.
How? GraphQL does not dictate how you get / mutate the data that the user has queried. It's up to your implementation to get the requested aggregated data. You could get aggregated data directly from your MongoDB and serve it back, or you get all the data you need from your data source and do the aggregation yourself.
If you are using Hasura, in the explorer, you can definitely see an "agregate" table name, thus, your query would look something similar to the following:
query queryTable {
table_name {
field1
field2
}
table_name_aggregate {
aggregate { count }
}
}
In your results, you will see the total row count for the query
"table_name_aggregate": {
"aggregate": {
"count": 9973
}
This depends on whether you build the aggregator into your schema and are able to resolve the field.
Can you share what kind of GraphQL Server you're running? As different languages have different implementations, as well as different services (like Hasura, 8base, and Prisma).
Also, when you say "counts", I'm imagining a count of objects in a relation. Such as:
query {
user(id: "1") {
name
summaries {
count
}
}
}
// returns
{
"data": {
"user": {
"name": "Steve",
"summaries": {
"count": 10
}
}
}
}
8base provides the count aggregate by default on relational queries.

Resources