Search code examples
react-nativeamazon-dynamodbaws-amplifydynamodb-queries

Aggregate on Save with AWS Amplify DataStore


I am trying to migrate a project that I previously had a Django backend for to a single AWS DataStore backend. So far so good but I am missing the equivalent of Django's 'property' command to have aggregate fields.

Essentially, I have a very simple schema in my app (backend of AppSync, DynamoDB):

type Account @model {
  id: ID!
  balance: Float!
  transactions: [Transaction] @connection(name: "transactions")
}

type Transaction @model {
  id: ID!
  note: String!
  amt: Float!
  account: Account @connection(name: "transactions")

And, I would like to find a way to quickly show the balance of the account (sum of all 'amt' values). I believe the best way to do this would be to update Balance on Account model once a new transaction is saved, but cannot work out correct way to do this.

What is best practice? Could someone share some examples?


Solution

  • You don't give enough details about your app to consider the number of transactions per account, etc. when making a suggestion so I may be way off base.

    Remembering that with Datastore all data is synced to local storage and all queries run against local storage so the cost of retrieving the desired transactions should be low. Therefore, why not just query for the transactions you want to sum and use reduce to aggregate the values.

    Here is a partly pseudo-code example.

    var transactions = result-of-query
    let initialValue = 0
    let sum = transactions.reduce(function (previousValue, currentTransaction) {
        return previousValue + currentTransaction.amt
    }, initialValue)