GraphQL Partial Update

GraphQL Partial Update

Originally appeared on medium: https://igor-kosta.medium.com/graphql-partial-update-783bf533a7fc

Recently we decided to use AWS Amplify for one of the products we’re currently working on.

AWS Amplify let you to relatively rapidly prototype your backend API either by using REST or GraphQL. We decided to go with GraphQL since in the final iterations the product should have different frontends and, theoretically, it should be easier to fetch only the data you need due to flexible nature of GraphQL.

So, if you worked with AWS Amplify and GraphQL you know that it doesn’t support partial updates, which was a deal breaker for us, since we have multiple flows where we have to partially push the data to the backend.

After a short research online, I found a pretty cool article from Arnaud Bezançon here https://medium.com/workflowgen/graphql-mutations-partial-updates-implementation-bff586bda989

Although I really liked his way of doing things, my lazy nature wanted to have a more generic (not necessarily a better) solution though. So, my way of thinking was: since I only send parts of the data to the backend but it expects the whole { input } object from me, I will just merge the existing data with the new one and push it to the backend.

The one more thing you have to consider though is to remove any automatically generated/updated fields on your schema — in my case createdAt/updatedAt

So, below you see a quick and dirty way of doing it.

Please, note that I’m using email as the key of our user model. Additionally to that you will have to always send the whole user object with all the fields to the update mutation — meaning when you call getUser you should fetch the user object with all the fields.


No alt text provided for this image

Since the email is used as the key of the user model, it have to be passed to the createOrUpdate function as part of the { input } object. Whenever I have to create or update a user, we have to add the email to the { input } and then just call createOrUpdate(input);

const { email } = user;
const input = { email, …payload };
try {
  ...
  await createOrUpdate(input);
  ...
} catch (error) {
  throw new Error(error);
}

It’s not an efficient way of doing things since it will fetch the data from your backend before doing an update but this way you don’t have to do things manually or thing about the values you’d like to be updated.

That’s all folks.


To view or add a comment, sign in

Others also viewed

Explore content categories