DEV Community

Cover image for Partial Success Graphql in Batch Operations
gaffleck
gaffleck

Posted on

2

Partial Success Graphql in Batch Operations

I really like Graphql. Since adopting it at Produce8, we've really enjoyed how it decouples backend and front-end concerns and allows for high re-use.

We recently hit a challenge and I wasn't able to find a lot of good samples online, so I thought I'd share what we did.

The Scenario

We have a batch operation (say add a tag to a photo), and each request has it's own validation implemented on the service (ie. ensure that you have update permissions on that specific photo record). So a batch of 10 addTag mutations might succeed for 9 and fail on 1. This didn't feel like an 'error' scenario, and the front-end will require the ID of the failed record to show a contextual error message to the end user. So here's how we handled it.

The Solution

First we implement our mutation API

type Mutation{
batchUpdatePhoto(input: BatchPhotoupdateInput!): [BatchPhotoupdateResponse!]!
}

input BatchPhotoupdateInput {
  pairs: [PhotoTagPairInput!]!
}

input PhotoTagPairInput {
  photoId: ID!
  tagId: ID!
}

Enter fullscreen mode Exit fullscreen mode

This allows a user to send a set of photos to be tagged. Each will be processed individually by the resolver on the serverside and list of responses will be returned.

Partial Success

Now for the tricky bit, we want to return the same number of responses as input pairs received and inform the user which failed to be parsed, so we need to do a union of a success message and the specific errors that could be returned.

union BatchPhotoupdateResponse = NotAuthorizedToUpdatePhotoError | Photo 

type NotAuthorizedToUpdatePhotoError implements CoreServiceError {
  code: String!
  message: String!
  photoId: ID!

}

interface CoreServiceError {
  code: String!
  message: String!
}

Enter fullscreen mode Exit fullscreen mode

By doing a union between the success and error response, we're able to return a single array of results to the client which can be both a success and error case.

Happy Coding!

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay