0
votes

there's something I suppose it should be easy but I can not find out the answer after searching the web for a long time:

I was just trying to make a mutation using graphql then refresh data using another graphql query afterwards, how can I make this happen inside only one HTTP(graphql) request?

Failed trys:

  1. I tried sending two graphql schemas wrapped inside one array use batching, but it's async and the query gets back before the mutation which is not desired.
  2. I tried to write the same query using mutation which actually mutates nothing and put that after the real mutation, this works but I don't believe this is the optimized solution for this.
  3. Also, I know there's something like update(refetchQuery) etc by apollo-client(react), but how can I do this without any client framework?

Thanks:)

related links:

1
Is it possible for you to modify the mutation result so that you get the query data directly without an additional query?Tal Z
Thanks, this is surely a good solution. But the problem is when I can not decide what the response should look like or there's more complicated data I need. I think these cases do exist, but your answer do works in your case.Octave W
In that case, maybe Interfaces and Union Types will help. You can read about them here: graphql.org/learn/schema I don't have experience using them, but maybe they could be part of the solution for your case.Tal Z

1 Answers

2
votes

If I understand you correctly you want to send a mutation and in the same request/query send a query that waits for the mutation to finish before being resolved. From the specifications perspective this is simply not possible (yet). You can read the specification here (I know technical specification sounds scary but if you are already a bit familiar with GraphQL it is easy to read :-) ).

The idea is that a mutation result is designed to potentially return the data that has been updated. I read in an article a while ago about the query object type. The article highlights how the type is just a normal object type and can be simply returned in a mutation result. While I would not recommend this pattern since I think the mutation result should explicitly list all updated objects it is certainly possible and can be a solution for very complicated cases (like the one you describe). To make this a bit more visual here is an example schema:

type ExampleMutationResult {
  success: Boolean!
  query: Query!
}

type Query {
  queryField: String!
}

type Mutation {
  exampleMutation: ExampleMutationResult!
}

# Query would look like this
mutation example {
  exampleMutation {
    success
    query {
      queryField
    }
  }
}

As you can see the tradeoff is relatively high and can only be enabled when you can change the schema. I would check first if the overhead of the second HTTP request really needs optimisation.