All files / users list-following.js

100% Statements 39/39
66.66% Branches 12/18
100% Functions 5/5
100% Lines 37/37

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                 3x   3x 3x 2x 2x   2x     1x 6x 6x 6x   6x 1x             5x 1x             4x 1x             3x         2x   2x     2x 2x   2x 2x 2x       2x     2x   2x   2x                     1x 1x               1x  
/**
 * GET /v1/users/{userId}/following
 *
 * Lists the users {userId} follows, newest-follow-first. Restricted to the
 * user themself (403 for anyone else) — see list-followers.js for the
 * rationale (lists are private, counts are public).
 *
 * @implements UC-PROFILE-007.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': '*'
}
 
// Follows every page (via LastEvaluatedKey) so a user following many accounts
// never has their list silently truncated before the in-memory offset
// pagination below.
async function queryAllPages(queryParams) {
  const items = []
  let ExclusiveStartKey
  do {
    const result = await docClient.send(new QueryCommand({ ...queryParams, ExclusiveStartKey }))
    items.push(...(result.Items || []))
    ExclusiveStartKey = result.LastEvaluatedKey
  } while (ExclusiveStartKey)
  return items
}
 
const listFollowingHandler = async (event) => {
  try {
    const userId = event.pathParameters?.userId
    const callerId = event.requestContext?.authorizer?.claims?.sub
 
    if (!callerId) {
      return {
        statusCode: 401,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Unauthorized' })
      }
    }
 
    if (!userId) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Missing user id' })
      }
    }
 
    if (callerId !== userId) {
      return {
        statusCode: 403,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'You can only view your own following list' })
      }
    }
 
    const follows = await queryAllPages({
      TableName: process.env.USER_FOLLOWS_TABLE_NAME,
      KeyConditionExpression: 'followerId = :userId',
      ExpressionAttributeValues: { ':userId': userId }
    })
    follows.sort((a, b) => (b.followedAt || '').localeCompare(a.followedAt || ''))
 
    const limit = event.queryStringParameters?.limit
      ? parseInt(event.queryStringParameters.limit, 10)
      : 30
    const nextToken = event.queryStringParameters?.nextToken
    const offset = nextToken ? parseInt(Buffer.from(nextToken, 'base64').toString(), 10) : 0
 
    const page = follows.slice(offset, offset + limit)
    const hasMore = offset + limit < follows.length
    const responseNextToken = hasMore
      ? Buffer.from(String(offset + limit)).toString('base64')
      : null
 
    const usersById = await resolvePublicUsers(
      docClient,
      process.env.USERS_TABLE_NAME,
      page.map((f) => f.followeeId)
    )
    const items = page.map((f) => usersById.get(f.followeeId)).filter(Boolean)
 
    return {
      statusCode: 200,
      headers: CORS_HEADERS,
      body: JSON.stringify({
        items,
        nextToken: responseNextToken,
        hasMore,
        total: follows.length
      })
    }
  } catch (error) {
    console.error('[list-following] Exception:', error.message, error.stack)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Failed to list following' })
    }
  }
}
 
module.exports = { listFollowingHandler }