Skip to content

Instantly share code, notes, and snippets.

@oharaandrew314
Last active December 8, 2022 01:44
Show Gist options
  • Save oharaandrew314/a9e848fc59be9dc26ffcb0917ab6d9b1 to your computer and use it in GitHub Desktop.
Save oharaandrew314/a9e848fc59be9dc26ffcb0917ab6d9b1 to your computer and use it in GitHub Desktop.
repositories {
maven { setUrl("https://jitpack.io") }
}
dependencies {
implementation("com.github.oharaandrew314:dynamodb-kotlin-module:0.2.0")
implementation("software.amazon.awssdk:dynamodb-enhanced:2.18.24")
}
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient
import io.andrewohara.dynamokt.DataClassTableSchema
fun main() {
val repository = DynamoDbEnhancedClient.create()
.table(System.getenv("TABLE_NAME"), DataClassTableSchema(DynamoCat::class))
.let { V2DynamoCatsRepo(it) }
// do stuff
}
import io.andrewohara.dynamokt.DynamoKtPartitionKey
import io.andrewohara.dynamokt.DynamoKtSecondaryPartitionKey
import io.andrewohara.dynamokt.DynamoKtSecondarySortKey
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable
import software.amazon.awssdk.enhanced.dynamodb.Key
import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional
import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest
import java.util.UUID
class V2DynamoCatsRepo(private val mapper: DynamoDbTable<DynamoCat>): CatsRepo {
override fun get(id: UUID) = mapper
.getItem(id.toKey())
?.toCat()
override fun plusAssign(cat: Cat) {
mapper.putItem(cat.toDynamo())
}
override fun minusAssign(id: UUID) {
mapper.deleteItem(id.toKey())
}
override fun listForOwner(ownerId: UUID): List<Cat> {
val req = QueryEnhancedRequest.builder()
.queryConditional(QueryConditional.keyEqualTo(ownerId.toKey()))
.build()
return mapper.index("owner")
.query(req)
.flatMap { it.items() }
.map { it.toCat() }
}
}
private fun UUID.toKey() = Key.builder().partitionValue(toString()).build()
data class DynamoCat(
@DynamoKtPartitionKey
@DynamoKtSecondarySortKey(["owner"])
val id: UUID,
@DynamoKtSecondaryPartitionKey(["owner"])
val ownerId: UUID,
val name: String
)
private fun DynamoCat.toCat() = Cat(id = id, ownerId = ownerId, name = name)
private fun Cat.toDynamo() = DynamoCat(id = id, ownerId = ownerId, name = name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment