All files / entities unsubscribe.js

100% Statements 33/33
93.33% Branches 14/15
100% Functions 1/1
100% Lines 32/32

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 114 115 116 117                    1x         1x 1x 1x   1x 1x   1x         1x 9x 9x 9x   9x 1x             8x 1x             7x             6x 1x             5x                 5x 5x         5x 5x   2x   1x     4x   4x           2x         1x             1x 1x               1x  
/**
 * DELETE /v1/entities/{entityId}/subscription
 *
 * Unsubscribe the calling user from a public entity. No RBAC permission
 * required — subscriptions are personal, so a user only ever manages their
 * own.
 *
 * @implements UC-CATALOG-005.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  GetCommand,
  TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const { buildSubscriberCountUpdate } = require('../utils/entitySubscriberCount')
const { isCountFloorCancellation } = require('../utils/counterFloor')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const CORS_HEADERS = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
const unsubscribeEntityHandler = async (event) => {
  try {
    const entityId = event.pathParameters?.entityId
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (!userId) {
      return {
        statusCode: 401,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Unauthorized' })
      }
    }
 
    if (!entityId) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Missing entity id' })
      }
    }
 
    const existingSubscription = await docClient.send(
      new GetCommand({
        TableName: process.env.ENTITY_SUBSCRIPTIONS_TABLE_NAME,
        Key: { userId, entityId }
      })
    )
 
    if (!existingSubscription.Item) {
      return {
        statusCode: 404,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Subscription not found' })
      }
    }
 
    const transactItems = [
      {
        Delete: {
          TableName: process.env.ENTITY_SUBSCRIPTIONS_TABLE_NAME,
          Key: { userId, entityId },
          ConditionExpression: 'attribute_exists(userId)'
        }
      }
    ]
    Eif (process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME) {
      transactItems.push(
        buildSubscriberCountUpdate(process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME, entityId, -1)
      )
    }
 
    try {
      await docClient.send(new TransactWriteCommand({ TransactItems: transactItems }))
    } catch (error) {
      if (!isCountFloorCancellation(error)) throw error
      // Count already at 0: still remove the subscription, leave the count alone.
      await docClient.send(new TransactWriteCommand({ TransactItems: transactItems.slice(0, 1) }))
    }
 
    console.log('[unsubscribe] Entity unsubscribed:', { userId, entityId })
 
    return {
      statusCode: 204,
      headers: CORS_HEADERS,
      body: ''
    }
  } catch (error) {
    if (
      error.name === 'ConditionalCheckFailedException' ||
      (error.name === 'TransactionCanceledException' &&
        error.CancellationReasons?.[0]?.Code === 'ConditionalCheckFailed')
    ) {
      return {
        statusCode: 404,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Subscription not found' })
      }
    }
 
    console.error('[unsubscribe] Exception:', error.message, error.stack)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Failed to unsubscribe from entity' })
    }
  }
}
 
module.exports = { unsubscribeEntityHandler }