All files / users list-blocks.js

100% Statements 34/34
92.85% Branches 13/14
100% Functions 5/5
100% Lines 33/33

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                                    1x 1x 1x   1x 1x   1x         1x 1x         1x       2x 2x     1x 10x 10x 10x 1x             9x 9x         9x 9x 2x 2x 1x           1x     8x                 7x   7x     5x       7x   7x 7x                   1x 1x              
/**
 * GET /v1/users/me/blocks
 *
 * Lists the users the caller blocked from Direct Messages, so their own
 * profile page can unblock them without finding each profile first. Self
 * only: who you blocked is never shown to anyone else.
 *
 * Paginated straight off the table's key order (blockedId) rather than by
 * block date: a date order would need a load-all-then-sort, and a page is
 * one Query whatever the size of the list.
 *
 * Query params:
 * - limit: page size (default 30, max 100)
 * - nextToken: opaque cursor from the previous page
 *
 * @implements UC-DM-009.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, QueryCommand } = require('@aws-sdk/lib-dynamodb')
const { resolvePublicUsers } = require('../utils/userFollows')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const CORS_HEADERS = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
const DEFAULT_LIMIT = 30
const MAX_LIMIT = 100
 
// The cursor only carries the last blockedId: the partition key is always
// the caller, so a token can never page through someone else's blocks.
function encodeCursor(lastEvaluatedKey) {
  return Buffer.from(lastEvaluatedKey.blockedId).toString('base64url')
}
 
function decodeCursor(token) {
  const blockedId = Buffer.from(token, 'base64url').toString()
  return blockedId || null
}
 
exports.handler = async (event) => {
  try {
    const blockerId = event.requestContext?.authorizer?.claims?.sub
    if (!blockerId) {
      return {
        statusCode: 401,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Unauthorized' })
      }
    }
 
    const rawLimit = parseInt(event.queryStringParameters?.limit, 10)
    const limit = Number.isFinite(rawLimit)
      ? Math.min(Math.max(rawLimit, 1), MAX_LIMIT)
      : DEFAULT_LIMIT
 
    let exclusiveStartKey
    const nextToken = event.queryStringParameters?.nextToken
    if (nextToken) {
      const blockedId = decodeCursor(nextToken)
      if (!blockedId) {
        return {
          statusCode: 400,
          headers: CORS_HEADERS,
          body: JSON.stringify({ error: 'Invalid nextToken' })
        }
      }
      exclusiveStartKey = { blockerId, blockedId }
    }
 
    const result = await docClient.send(
      new QueryCommand({
        TableName: process.env.USER_BLOCKS_TABLE_NAME,
        KeyConditionExpression: 'blockerId = :blockerId',
        ExpressionAttributeValues: { ':blockerId': blockerId },
        Limit: limit,
        ExclusiveStartKey: exclusiveStartKey
      })
    )
    const blocks = result.Items || []
 
    const usersById = await resolvePublicUsers(
      docClient,
      process.env.USERS_TABLE_NAME,
      blocks.map((b) => b.blockedId)
    )
    // A block on an account deleted since is dropped by the deletion cascade;
    // until then it just has no user to show.
    const items = blocks.map((b) => usersById.get(b.blockedId)).filter(Boolean)
 
    const hasMore = Boolean(result.LastEvaluatedKey)
    return {
      statusCode: 200,
      headers: CORS_HEADERS,
      body: JSON.stringify({
        items,
        nextToken: hasMore ? encodeCursor(result.LastEvaluatedKey) : null,
        hasMore
      })
    }
  } catch (error) {
    console.error('[users/list-blocks] Exception:', error.message, error.stack)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Failed to list blocked users' })
    }
  }
}