All files / utils entityRefUsages.js

100% Statements 23/23
80% Branches 8/10
100% Functions 8/8
100% Lines 18/18

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 56 57 581x   1x                                 4x                   4x   3x   2x     4x   2x 2x 2x 2x 2x   2x     2x   2x 2x     2x     1x  
const { QueryCommand, BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
 
const BATCH_SIZE = 25
 
/**
 * Finds public entities, owned by the same user as `ownerUserId`, whose fields
 * contain an entity_ref (item link) pointing to `entityId`. Used to block an
 * entity from being demoted from public while another public entity of the
 * same user still relies on it staying public (see validatePublicEntityFields,
 * which requires entity_ref targets of a public entity to be public).
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {{ entitiesTableName: string, flowsTableName: string, entityId: string, ownerUserId?: string }} params
 * @returns {Promise<Array>} public entities of the same user that reference entityId
 */
async function getPublicEntityRefUsers(
  docClient,
  { entitiesTableName, flowsTableName, entityId, ownerUserId }
) {
  const publicEntitiesResult = await docClient.send(
    new QueryCommand({
      TableName: entitiesTableName,
      IndexName: 'visibilityIndex',
      KeyConditionExpression: 'visibility = :visibility',
      FilterExpression: 'id <> :entityId',
      ExpressionAttributeValues: { ':visibility': 'public', ':entityId': entityId }
    })
  )
 
  const referencingEntities = (publicEntitiesResult.Items || []).filter(
    (entity) =>
      Array.isArray(entity.fields) &&
      entity.fields.some(
        (field) => field.type === 'entity_ref' && field.reference?.entityId === entityId
      )
  )
  if (referencingEntities.length === 0) return []
 
  const flowIds = [...new Set(referencingEntities.map((entity) => entity.flowId))]
  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 = new Set(
    flows.filter((flow) => flow.ownerId === ownerUserId).map((flow) => flow.id)
  )
 
  return referencingEntities.filter((entity) => sameUserFlowIds.has(entity.flowId))
}
 
module.exports = { getPublicEntityRefUsers }