All files / store update.js

100% Statements 50/50
97.91% Branches 47/48
100% Functions 2/2
100% Lines 47/47

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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113                                    1x 1x         1x 1x 1x 1x 1x   1x   1x 15x 15x 15x     14x 14x   1x   13x 13x 13x 12x 1x     11x 11x 10x 1x   9x 1x     8x 8x 8x 6x 6x   8x 1x 1x   8x 8x             8x 8x                     2x 1x   1x       6x 2x 2x       6x           1x 1x      
/**
 * PUT /v1/store/{packId}
 *
 * Changes a pack's settings, for those who may delete it (its author, the owner
 * of its flow, a platform admin). Body: { commentsEnabled?: boolean,
 * picture?: string | null }, at least one of them.
 *
 * Switching comments off hides the approved ones without deleting them; the
 * ones still awaiting review are removed as reviewers meet them, as on an
 * entity — see docs/architecture/MODERATION.md.
 *
 * The picture, shown on the pack's card, is a key uploaded under the pack
 * (`packs/{packId}/pack-picture/`); `null` removes it. The one it replaces is
 * deleted, best-effort.
 *
 * @implements UC-STORE-009.1, UC-STORE-014.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
const {
  authenticateModerator: authenticateUser,
  errorResponse,
  jsonResponse
} = require('../utils/moderation/access')
const { getPack, packsTable, isPackPictureKey, packPicturePrefix } = require('../utils/packs')
const { canDeletePack } = require('../utils/packAccess')
const { s3Client } = require('../utils/packSnapshot')
const { deleteKeys } = require('../utils/s3Cleanup')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
exports.handler = async (event) => {
  try {
    const caller = await authenticateUser(event)
    if (caller.response) return caller.response
 
    let payload
    try {
      payload = JSON.parse(event.body || '{}')
    } catch {
      return errorResponse(400, 'Invalid JSON body')
    }
    const setsComments = payload.commentsEnabled !== undefined
    const setsPicture = payload.picture !== undefined
    if (!setsComments && !setsPicture) return errorResponse(400, 'Nothing to update')
    if (setsComments && typeof payload.commentsEnabled !== 'boolean') {
      return errorResponse(400, 'commentsEnabled must be a boolean')
    }
 
    const pack = await getPack(docClient, event.pathParameters?.packId)
    if (!pack) return errorResponse(404, 'Pack not found')
    if (setsPicture && payload.picture !== null && !isPackPictureKey(pack.id, payload.picture)) {
      return errorResponse(400, 'PACK_PICTURE_INVALID')
    }
    if (!(await canDeletePack(docClient, pack, caller.auth.userId))) {
      return errorResponse(403, 'Permission denied')
    }
 
    const sets = []
    const values = {}
    if (setsComments) {
      sets.push('commentsEnabled = :enabled')
      values[':enabled'] = payload.commentsEnabled
    }
    if (setsPicture && payload.picture !== null) {
      sets.push('picture = :picture')
      values[':picture'] = payload.picture
    }
    const removesPicture = setsPicture && payload.picture === null
    const expression = [
      sets.length > 0 && `SET ${sets.join(', ')}`,
      removesPicture && 'REMOVE picture'
    ]
      .filter(Boolean)
      .join(' ')
 
    try {
      await docClient.send(
        new UpdateCommand({
          TableName: packsTable(),
          Key: { id: pack.id },
          UpdateExpression: expression,
          // Not recreated if deleted meanwhile
          ConditionExpression: 'attribute_exists(id)',
          ...(Object.keys(values).length > 0 && { ExpressionAttributeValues: values })
        })
      )
    } catch (error) {
      if (error.name === 'ConditionalCheckFailedException') {
        return errorResponse(404, 'Pack not found')
      }
      throw error
    }
 
    // The picture replaced is the pack's own object: never anything else
    if (setsPicture && pack.picture && pack.picture !== payload.picture) {
      await deleteKeys(s3Client, process.env.ATTACHMENTS_BUCKET_NAME, [pack.picture], (key) =>
        key.startsWith(packPicturePrefix(pack.id))
      )
    }
 
    return jsonResponse(200, {
      id: pack.id,
      commentsEnabled: setsComments ? payload.commentsEnabled : pack.commentsEnabled === true,
      picture: setsPicture ? payload.picture : (pack.picture ?? null)
    })
  } catch (error) {
    console.error('[store/update] Exception:', error.message, error.stack)
    return errorResponse(500, 'Failed to update pack')
  }
}