All files / utils entityLinks.js

100% Statements 22/22
75% Branches 6/8
100% Functions 3/3
100% Lines 20/20

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 55 564x   4x                           14x                 40x 14x 7x     7x 7x 8x 8x   40x     8x     7x 7x 7x 41x 5x   36x       7x     4x  
const { QueryCommand, BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
 
const BATCH_SIZE = 25
 
/**
 * Resolves the flows that link a given entity, split by whether the linking
 * flow is owned by the same user as `ownerUserId` or by someone else.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {{ entityLinksTableName: string, flowsTableName: string, entityId: string, ownerUserId?: string }} params
 * @returns {Promise<{ sameUserFlowIds: string[], otherUserFlowIds: string[] }>}
 */
async function getEntityLinkFlows(
  docClient,
  { entityLinksTableName, flowsTableName, entityId, ownerUserId }
) {
  const linksResult = await docClient.send(
    new QueryCommand({
      TableName: entityLinksTableName,
      IndexName: 'entityIndex',
      KeyConditionExpression: 'entityId = :entityId',
      ExpressionAttributeValues: { ':entityId': entityId }
    })
  )
 
  const flowIds = [...new Set((linksResult.Items || []).map((link) => link.flowId))]
  if (flowIds.length === 0) {
    return { sameUserFlowIds: [], otherUserFlowIds: [] }
  }
 
  const flows = []
  for (let i = 0; i < flowIds.length; i += BATCH_SIZE) {
    const chunk = flowIds.slice(i, i + BATCH_SIZE)
    const batchResult = await docClient.send(
      new BatchGetCommand({
        RequestItems: { [flowsTableName]: { Keys: chunk.map((flowId) => ({ id: flowId })) } }
      })
    )
    flows.push(...(batchResult.Responses?.[flowsTableName] || []))
  }
 
  const sameUserFlowIds = []
  const otherUserFlowIds = []
  for (const flow of flows) {
    if (flow.ownerId === ownerUserId) {
      sameUserFlowIds.push(flow.id)
    } else {
      otherUserFlowIds.push(flow.id)
    }
  }
 
  return { sameUserFlowIds, otherUserFlowIds }
}
 
module.exports = { getEntityLinkFlows }