All files / moderation submissions.js

100% Statements 39/39
100% Branches 24/24
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                                  1x 1x 1x 1x 1x   1x 1x   1x 1x   1x 14x 14x 14x 13x   13x 13x         13x 13x 3x 3x   2x 1x   2x       11x         10x 10x 9x 9x 8x 8x   7x     7x                   10x             1x 1x      
/**
 * GET /v1/moderation/submissions
 *
 * The caller's own recent submissions with their status (pending, approved or
 * rejected), newest first, paginated. Decided ones stay for a month (see
 * DECIDED_TASK_TTL_SECONDS), so this is recent history, not an archive.
 * A submission met pending with its threshold already reached (its deciding
 * transaction failed) is decided on the way: in a small community its author
 * may be the only one left who ever meets it.
 *
 * Query params:
 * - limit: page size (default 10, max 20)
 * - nextToken: opaque cursor returned by the previous page
 *
 * @implements UC-MOD-010.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb')
const { authenticateModerator, errorResponse, jsonResponse } = require('../utils/moderation/access')
const { listSubmissions, settleReachedDecision } = require('../utils/moderation/engine')
const { getSubject } = require('../utils/moderation/subjects')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const DEFAULT_LIMIT = 10
const MAX_LIMIT = 20
 
exports.handler = async (event) => {
  try {
    const caller = await authenticateModerator(event)
    if (caller.response) return caller.response
    const { auth } = caller
 
    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) {
      try {
        const key = JSON.parse(Buffer.from(nextToken, 'base64').toString())
        // A client-controlled cursor must not point the Query at another user
        if (key?.authorId !== auth.userId || typeof key.taskId !== 'string') throw new Error('bad')
        exclusiveStartKey = { taskId: key.taskId, authorId: key.authorId, sortKey: key.sortKey }
      } catch {
        return errorResponse(400, 'Invalid nextToken')
      }
    }
 
    const { tasks, lastEvaluatedKey } = await listSubmissions(docClient, auth.userId, {
      limit,
      exclusiveStartKey
    })
 
    const submissions = []
    for (const task of tasks) {
      const subject = getSubject(task.subjectType)
      if (!subject) continue
      const context = await subject.loadContext(docClient, task)
      if (context === null) continue // the content is gone
      // An unreviewable subject is left for the review queue to discard
      const settled = subject.isReviewable(context)
        ? await settleReachedDecision(docClient, { task, subject, context })
        : null
      submissions.push({
        taskId: task.taskId,
        subjectType: task.subjectType,
        status: settled ?? task.status,
        createdAt: task.createdAt,
        decidedAt: settled ? new Date().toISOString() : (task.decidedAt ?? null),
        view: subject.describe(context)
      })
    }
 
    return jsonResponse(200, {
      submissions,
      nextToken: lastEvaluatedKey
        ? Buffer.from(JSON.stringify(lastEvaluatedKey)).toString('base64')
        : null
    })
  } catch (error) {
    console.error('[moderation/submissions] Exception:', error.message, error.stack)
    return errorResponse(500, 'Failed to list submissions')
  }
}