All files / admin list-flows.js

100% Statements 23/23
100% Branches 18/18
100% Functions 5/5
100% Lines 23/23

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                            1x 1x 1x         1x 1x 1x 1x   1x   1x           3x                           1x 7x 7x       6x                   3x       5x   3x     5x       3x           2x 1x           1x 1x              
/**
 * List Flows (Platform Admin) Lambda
 * GET /v1/platform-admin/flows?search=&limit=&cursor=
 *
 * Requires `isPlatformAdmin: true`. Platform-wide flow list, cursor-paginated, never
 * a table Scan, each row enriched with its owner's name/email. Newest first when
 * browsing (`platformStatsIndex`); with `search`, the trigram directory index
 * (case-insensitive substring on flow name and slug — see
 * utils/directorySearchIndex.js; results are not date-ordered) or, when the search
 * is a flow id, a direct lookup.
 *
 * @implements UC-ADMIN-006.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb')
const { requirePlatformAdmin } = require('../utils/requirePlatformAdmin')
const {
  InvalidListParamsError,
  parseListParams,
  batchGetByIds
} = require('../utils/platformAdminList')
const { listPlatformDirectory } = require('../utils/platformAdminDirectory')
const { FLOW_NAMESPACES, containsQuery } = require('../utils/directorySearchIndex')
const { isValidUuid } = require('../utils/isValidUuid')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
const corsHeaders = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
function toAdminFlow(flow, owner) {
  return {
    id: flow.id,
    name: flow.name,
    slug: flow.slug,
    description: flow.description || null,
    status: flow.status || 'active',
    joinPolicy: flow.joinPolicy || null,
    ownerId: flow.ownerId,
    ownerName: owner?.name || null,
    ownerEmail: owner?.email || null,
    createdAt: flow.createdAt || null
  }
}
 
exports.handler = requirePlatformAdmin(async (event) => {
  try {
    const list = parseListParams(event)
 
    // A flow id is exact, not fuzzy — resolve it directly instead of trigram-searching a UUID.
    const { items, nextCursor, truncated } =
      list.search && isValidUuid(list.search)
        ? {
            items: [...(await batchGetByIds(process.env.FLOWS_TABLE_NAME, [list.search])).values()],
            nextCursor: null,
            truncated: false
          }
        : await listPlatformDirectory(docClient, {
            subjectsTableName: process.env.FLOWS_TABLE_NAME,
            gsiPkValue: 'FLOW',
            namespaces: FLOW_NAMESPACES,
            verify: (flow, query) => containsQuery(query, [flow.name, flow.slug]),
            list
          })
 
    const owners = await batchGetByIds(
      process.env.USERS_TABLE_NAME,
      items.map((flow) => flow.ownerId).filter(Boolean)
    )
 
    return {
      statusCode: 200,
      headers: corsHeaders,
      body: JSON.stringify({
        items: items.map((flow) => toAdminFlow(flow, owners.get(flow.ownerId))),
        nextCursor,
        truncated
      })
    }
  } catch (error) {
    if (error instanceof InvalidListParamsError) {
      return {
        statusCode: 400,
        headers: corsHeaders,
        body: JSON.stringify({ error: error.message })
      }
    }
    console.error('Error listing platform flows:', error)
    return {
      statusCode: 500,
      headers: corsHeaders,
      body: JSON.stringify({ error: 'Failed to list flows' })
    }
  }
})