All files / space-pages order.js

97.82% Statements 45/46
90.9% Branches 20/22
100% Functions 9/9
97.29% Lines 36/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                      1x 1x 1x 1x   1x       10x 10x 15x 6x     1x 13x 13x 13x 12x 12x     11x 11x   1x   10x 10x   5x     16x 10x 1x     3x 8x 8x 3x 2x 2x   4x                         1x 1x           6x   1x 1x      
// @implements UC-SPACE-009.1
/**
 * PUT /v1/flows/{flowId}/pages  (`pages:update`)
 *
 * Orders the space menu: `{ order: [pageSlug, ...] }` gives each page named
 * its index as `menuOrder`, in one transaction. The editor drags a page among
 * the others, so inserting one between two never asks for their numbers. The
 * pages left out keep theirs (pages not in the menu, typically). Neither the
 * draft nor `updatedAt` change: the order is no edit of a page, and an editor
 * open on one of them can still save it.
 */
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, TransactWriteCommand } = require('@aws-sdk/lib-dynamodb')
const { isPageSlug, LIMITS } = require('../utils/spacePages')
const { respond, listPages, memberAccess, forbidden } = require('./shared')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
/** The slugs, when the body names each page at most once */
function validOrder(body) {
  const order = body?.order
  if (!Array.isArray(order) || order.length > LIMITS.pagesPerFlow) return null
  if (!order.every((slug) => isPageSlug(slug))) return null
  return new Set(order).size === order.length ? order : null
}
 
exports.handler = async (event) => {
  try {
    const access = await memberAccess(event)
    if (access.response) return access.response
    const { flowId, canEdit } = access
    if (!canEdit) return forbidden()
 
    let body
    try {
      body = JSON.parse(event.body || '{}')
    } catch {
      return respond(400, { error: 'Invalid JSON body' })
    }
    const order = validOrder(body)
    if (!order) return respond(400, { error: 'order must list distinct page slugs' })
 
    const pages = await listPages(docClient, flowId, {
      ProjectionExpression: 'slug, menuOrder'
    })
    const current = new Map(pages.map((page) => [page.slug, page.menuOrder]))
    if (order.some((slug) => !current.has(slug))) {
      return respond(404, { error: 'Page not found' })
    }
 
    const moved = order
      .map((slug, menuOrder) => ({ slug, menuOrder }))
      .filter(({ slug, menuOrder }) => current.get(slug) !== menuOrder)
    if (moved.length) {
      try {
        await docClient.send(
          new TransactWriteCommand({
            TransactItems: moved.map(({ slug, menuOrder }) => ({
              Update: {
                TableName: process.env.FLOW_PAGES_TABLE_NAME,
                Key: { flowId, slug },
                // A page deleted meanwhile is not created again
                ConditionExpression: 'attribute_exists(slug)',
                UpdateExpression: 'SET menuOrder = :menuOrder',
                ExpressionAttributeValues: { ':menuOrder': menuOrder }
              }
            }))
          })
        )
      } catch (error) {
        Eif (error.name === 'TransactionCanceledException') {
          return respond(404, { error: 'Page not found' })
        }
        throw error
      }
    }
 
    return respond(200, { order: order.map((slug, menuOrder) => ({ slug, menuOrder })) })
  } catch (error) {
    console.error('Error ordering the space pages:', error)
    return respond(500, { error: 'Failed to order pages' })
  }
}