How to create a generic method to save any type in DynamoDB using AWS SDK 2.x?

Viewed 25

I wrote this code using Kotlin to save both an Artist and Song in a Dynamo table:

fun saveModel(model: DynamoBaseModel){
    try {
        when(model){
            is Artist -> {
                val artistTable: DynamoDbTable<Artist> =
                    enhancedClient.table("music", TableSchema.fromBean(Artist::class.java))
                artistTable.putItem(model)
            }
            is Song -> {
                val songTable: DynamoDbTable<Song> =
                    enhancedClient.table("music", TableSchema.fromBean(Song::class.java))
                songTable.putItem(model)
            }
        }
    }catch (e: DynamoDbException){
        e.printStackTrace()
    }
}

You can take a look at the project I'm using to test AWS SDK 2.x stuff here. This specific method is in this file. How can I transform this method in a generic one? It seems the putItem from SDK does not accept an object of the parent type (DynamoBaseModel), so I must cast it to the child type (Artist or Song). Another thing that makes it hard to create a generic method is that I need to inform the type in this part DynamoDbTable<Artist> and in this part TableSchema.fromBean(Artist::class.java). It turns out that if come up more and more model classes, the number of conditionals inside this method would increase as well and I would end up with a huge method. Besides that, if I need a conditional around putItem, I would have to put it inside each when condition and this duplication would be very bad. Any thoughts?

Thank you.

0 Answers
Related