All files / users follow.js

100% Statements 35/35
94.11% Branches 16/17
100% Functions 1/1
100% Lines 35/35

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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141                    1x         1x 1x   1x 1x   1x         1x 11x 11x 11x   11x 1x             10x 1x             9x 1x             8x             7x 1x             6x             6x 1x             5x 5x             5x                 5x 5x         5x   4x   4x           2x         1x             1x 1x               1x  
/**
 * POST /v1/users/{userId}/follow
 *
 * Follow another user. Open, one-directional, no approval step (like
 * entities/subscribe.js's subscription model) and no RBAC permission
 * requirement — this is a personal action, not a functional data dependency.
 *
 * @implements UC-PROFILE-006.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  GetCommand,
  TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const { buildFollowerCountUpdate } = require('../utils/userFollows')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const CORS_HEADERS = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
const followUserHandler = async (event) => {
  try {
    const followeeId = event.pathParameters?.userId
    const followerId = event.requestContext?.authorizer?.claims?.sub
 
    if (!followerId) {
      return {
        statusCode: 401,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Unauthorized' })
      }
    }
 
    if (!followeeId) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Missing user id' })
      }
    }
 
    if (followeeId === followerId) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Cannot follow yourself' })
      }
    }
 
    const followeeResult = await docClient.send(
      new GetCommand({
        TableName: process.env.USERS_TABLE_NAME,
        Key: { id: followeeId }
      })
    )
 
    if (!followeeResult.Item) {
      return {
        statusCode: 404,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'User not found' })
      }
    }
 
    const existingFollow = await docClient.send(
      new GetCommand({
        TableName: process.env.USER_FOLLOWS_TABLE_NAME,
        Key: { followerId, followeeId }
      })
    )
 
    if (existingFollow.Item) {
      return {
        statusCode: 409,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Already following this user' })
      }
    }
 
    const now = new Date().toISOString()
    const follow = { followerId, followeeId, followedAt: now }
 
    // The follow Put and the follower-count +1 must succeed or fail together
    // — otherwise a crash between the two would leave the counter permanently
    // out of sync with the actual follow rows. The ConditionExpression
    // (rather than relying solely on the pre-check Get above) also closes the
    // race where two concurrent follow requests both pass that check.
    const transactItems = [
      {
        Put: {
          TableName: process.env.USER_FOLLOWS_TABLE_NAME,
          Item: follow,
          ConditionExpression: 'attribute_not_exists(followerId)'
        }
      }
    ]
    Eif (process.env.USER_FOLLOWER_COUNT_TABLE_NAME) {
      transactItems.push(
        buildFollowerCountUpdate(process.env.USER_FOLLOWER_COUNT_TABLE_NAME, followeeId, 1)
      )
    }
 
    await docClient.send(new TransactWriteCommand({ TransactItems: transactItems }))
 
    console.log('[follow] User followed:', { followerId, followeeId })
 
    return {
      statusCode: 201,
      headers: CORS_HEADERS,
      body: JSON.stringify(follow)
    }
  } catch (error) {
    if (
      error.name === 'ConditionalCheckFailedException' ||
      (error.name === 'TransactionCanceledException' &&
        error.CancellationReasons?.[0]?.Code === 'ConditionalCheckFailed')
    ) {
      return {
        statusCode: 409,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Already following this user' })
      }
    }
 
    console.error('[follow] Exception:', error.message, error.stack)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Failed to follow user' })
    }
  }
}
 
module.exports = { followUserHandler }