All files / utils userUsageCleanup.js

100% Statements 11/11
50% Branches 1/2
100% Functions 3/3
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 522x 2x                 27x 28x                   28x     8x         28x                               9x 9x 9x     2x  
const { QueryCommand } = require('@aws-sdk/lib-dynamodb')
const { batchDelete } = require('./batchWrite')
 
/**
 * Deletes every row a user owns in one of the userId-partitioned metering
 * tables. `day` and `month` are DynamoDB reserved words, hence the attribute
 * name placeholders.
 */
async function deleteAllRowsForUser(docClient, tableName, userId, sortKeyName) {
  let lastKey
  do {
    const result = await docClient.send(
      new QueryCommand({
        TableName: tableName,
        KeyConditionExpression: '#pk = :userId',
        ExpressionAttributeNames: { '#pk': 'userId', '#sk': sortKeyName },
        ExpressionAttributeValues: { ':userId': userId },
        ProjectionExpression: '#pk, #sk',
        ExclusiveStartKey: lastKey
      })
    )
    await batchDelete(
      docClient,
      tableName,
      (result.Items || []).map((item) => ({
        userId: item.userId,
        [sortKeyName]: item[sortKeyName]
      }))
    )
    lastKey = result.LastEvaluatedKey
  } while (lastKey)
}
 
/**
 * Purges a user's credits ledger and daily/monthly usage summaries. Meant
 * for throwaway accounts only (see e2eTestUser.js): for a real user these
 * tables are an accounting trail that outlives the account.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {{ creditsLedgerTableName: string, usageDailyTableName: string, usageMonthlyTableName: string, userId: string }} params
 */
async function deleteCreditsAndUsageForUser(
  docClient,
  { creditsLedgerTableName, usageDailyTableName, usageMonthlyTableName, userId }
) {
  await deleteAllRowsForUser(docClient, creditsLedgerTableName, userId, 'transactionId')
  await deleteAllRowsForUser(docClient, usageDailyTableName, userId, 'day')
  await deleteAllRowsForUser(docClient, usageMonthlyTableName, userId, 'month')
}
 
module.exports = { deleteCreditsAndUsageForUser }