Search code examples
amazon-web-servicesgraphqlamazon-dynamodbaws-amplifyaws-appsync

How should you alter user-provided data before it's inserted in DynamoDB GraphQL table?


I'm using AWS Amplify / DynamoDB / AppSync to build a chat app and I want to be able to censor profanity in chat messages.

I don't want to do this client-side because the user can work around that. I don't want to handle it in a Lambda because I want to use gql subscriptions to deliver chat messages in real time (i.e. I want to handle it before it's inserted in the database).

Is the correct way to handle this in the Mutation request resolver? I have a version of that working now but it seems like a long walk around the block to handle this. I also have to remember to update my resolver if I change my auth configuration.


Solution

  • You need a mutation which modifies chat messages, and then inserts them to DynamoDb. If the logic of message modification is simple, then you can implement the mutation with a DynamoDb resolver. Otherwise, you go with a direct-lambda resolver.

    Your AppSync subscription should work fine with a direct lambda resolver. It can receive whatever you return from the lambda. For instance: the subscription below can receive both original/altered message contents.

    type Mutation {
      sendMessage(input: MessageInput!): SendMessageResult
    }
    
    type Subscription: {
      onMessageReceived(receivedUserId: ID!): SendMessageResult
        @aws_subscribe(mutations: ["sendMessage"])
    }
    
    type SendMessageResult {
      messageId
      originalMessageContent
      alteredMessageContent
      receivedUserId
      sentUserId
      sentAt
    }