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!
}
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!
}
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!
Top comments (0)