All files / utils packSource.js

100% Statements 23/23
100% Branches 12/12
100% Functions 5/5
100% Lines 19/19

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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73                          3x     3x     3x 3x 3x 4x       154x             3x   2x     2x               192x 34x     3x 3x   1x 1x     2x 155x                         3x  
/**
 * Where a copy installed from a Store pack comes from, as the entity page and
 * the entity list show it: "From Small CRM (v1)" (UC-STORE-016.1). The copy's
 * `packOrigin` holds the pack's id and the version it is at; the name is the
 * pack's current one, read here, `null` once the pack is deleted.
 *
 * One `BatchGet` of the distinct packs of the entities given, bounded by the
 * page size. Best-effort: when the packs cannot be read, the entities go
 * without `fromPack`, and the page still loads.
 *
 * @implements UC-STORE-016.1
 */
 
const { BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
 
/** DynamoDB BatchGetItem accepts at most 100 keys per request. */
const BATCH_GET_LIMIT = 100
 
async function readPackNames(docClient, packIds) {
  const tableName = process.env.PACKS_TABLE_NAME
  const names = new Map()
  for (let offset = 0; offset < packIds.length; offset += BATCH_GET_LIMIT) {
    const result = await docClient.send(
      new BatchGetCommand({
        RequestItems: {
          [tableName]: {
            Keys: packIds.slice(offset, offset + BATCH_GET_LIMIT).map((id) => ({ id })),
            ProjectionExpression: 'id, #name, currentVersion',
            ExpressionAttributeNames: { '#name': 'name' }
          }
        }
      })
    )
    for (const pack of result.Responses?.[tableName] || []) {
      // A row without a published version is no pack anyone can see
      if (pack.currentVersion) names.set(pack.id, pack.name)
    }
  }
  return names
}
 
/**
 * The entities, each copy with `fromPack: { packId, version, name }`, `name`
 * being null for a pack deleted since.
 */
async function withPackSources(docClient, entities) {
  const packIds = [...new Set(entities.map((entity) => entity.packOrigin?.packId).filter(Boolean))]
  if (packIds.length === 0 || !process.env.PACKS_TABLE_NAME) return entities
 
  let names
  try {
    names = await readPackNames(docClient, packIds)
  } catch (error) {
    console.error('[packSource] Could not read the packs of copies:', error.message)
    return entities
  }
 
  return entities.map((entity) =>
    entity.packOrigin?.packId
      ? {
          ...entity,
          fromPack: {
            packId: entity.packOrigin.packId,
            version: entity.packOrigin.version,
            name: names.get(entity.packOrigin.packId) ?? null
          }
        }
      : entity
  )
}
 
module.exports = { withPackSources }