Search code examples
amazon-web-servicesgraphqlamazon-dynamodbaws-amplifyaws-amplify-cli

How to prevent losing production data when changing my GraphQL schema in AWS Amplify?


In my AWS Amplify project I am using a GraphQL API with several @model directives. Therefore, Amplify generated multiple DynamoDB tables in my AWS backend. Now, when removing such a @model or renaming it, the old DynamoDB table will be permanently deleted with all the contained data!

How can this be prevented to avoid production data by mistake?


Solution

  • To prevent your DynamoDB tables from being deleted you can set the DeletionPolicy to Retain. Unfortunately, Amplify does not do this by default.

    Therefore, you can use the custom GraphQL directive @retain like this:

    1. Install the transformer: npm install --save graphql-retain-transformer.
    2. Edit amplify/backend/api/<YOUR_API>/transform.conf.json and append "graphql-retain-transformer" to the transformers field:
    "transformers": [
        "graphql-retain-transformer"
    ]
    
    1. In your schema.graphql file, append the @retain directive to all the @model types that you want to activate the Retain Deletion Policy for:
    type Todo @model @retain {
      id: ID!
      title: String!
      description: String
    }
    

    GitHub repository of the custom directive: https://github.com/flogy/graphql-retain-transformer (please leave a ⭐️ if you like it 🙂)

    A more detailed blog post about it: https://react-freelancer.ch/blog/amplify-retain-dynamodb-tables