All files / utils membershipRoleCleanup.js

100% Statements 16/16
75% Branches 6/8
100% Functions 2/2
100% Lines 13/13

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 52 53 54 554x 4x                               11x   6x                 6x 6x 9x 15x 9x   5x                       5x       6x     4x  
const { QueryCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
const { notifyPermissionsChanged } = require('./permissionsChangedPush')
 
/**
 * Strips the given role ids from every membership's `roleIds` in a flow —
 * shared by any code path that removes a role (direct deletion via
 * roles/delete.js, or the indirect cascade in entityDeletionRoleCleanup.js
 * when a role is emptied out by an entity deletion) so a membership never
 * keeps pointing at a role that no longer exists.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {{ flowMembershipsTableName: string, flowId: string, roleIds: string[] }} params
 */
async function removeRoleIdsFromMemberships(
  docClient,
  { flowMembershipsTableName, flowId, roleIds }
) {
  if (roleIds.length === 0) return
 
  const membershipsResult = await docClient.send(
    new QueryCommand({
      TableName: flowMembershipsTableName,
      IndexName: 'flowIndex',
      KeyConditionExpression: 'flowId = :flowId',
      ExpressionAttributeValues: { ':flowId': flowId }
    })
  )
 
  const updatedUserIds = []
  for (const membership of membershipsResult.Items || []) {
    const currentRoleIds = membership.roleIds || []
    const remainingRoleIds = currentRoleIds.filter((roleId) => !roleIds.includes(roleId))
    if (remainingRoleIds.length === currentRoleIds.length) continue
 
    await docClient.send(
      new UpdateCommand({
        TableName: flowMembershipsTableName,
        Key: { userId: membership.userId, flowId: membership.flowId },
        UpdateExpression: 'SET #roleIds = :roleIds, #updatedAt = :updatedAt',
        ExpressionAttributeNames: { '#roleIds': 'roleIds', '#updatedAt': 'updatedAt' },
        ExpressionAttributeValues: {
          ':roleIds': remainingRoleIds,
          ':updatedAt': new Date().toISOString()
        }
      })
    )
    updatedUserIds.push(membership.userId)
  }
 
  // The members who lost a role reload their permissions right away
  await notifyPermissionsChanged(updatedUserIds, flowId)
}
 
module.exports = { removeRoleIdsFromMemberships }