Search code examples
aws-appsync

Validating array input in AppSync Resolver Template


I have a query in my aws app-sync:

input TestingInput {
    user_ids: [String]!
}

Now, I need to do 2 different validations here:

  1. Validate that the user_ids is an array of strings.
  2. Validate that all user_ids exists in database.

For 1, I can use $util.isList(), but it cannot verify the if there is empty string of not. Is there any way we can filter out the empty string from array and then check the length of array?
For 2, no idea as of right now


Solution

    1. Velocity scripting has access to some Java API. In this case, they're lists, and strings. However, I'm not sure what Java version AppSync supports. From AWS documentation, it's being linked to Java SE 6. Go back to your problem, it's done by having a new list, and add non-empty ids into it.

      #set( $nonEmptyUserIds = [] )
      #foreach( $userId in $userIds )
        #set( $trimmedUserId = $userId.trim() )
        #if( $trimmedUserId.length() != 0 )
          $util.qr( $nonEmptyUserIds.add($trimmedUserId) )
        #end
      #end
      
    2. Since it's a check against your database, you need a datasource for your resolver, and a db query for the request mapping. If your db is a RDS, then you can use a SELECT. If it's a DyanmoDb, then BatchGetItem is the right choice.

    In the response mapping, you should have db results to validate submitted user ids.