All files / space-pages publish.js

96.15% Statements 50/52
87.5% Branches 21/24
100% Functions 1/1
95.55% Lines 43/45

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                        3x 3x 3x 3x                     3x   3x   3x 18x 18x 18x 16x 16x   15x 15x     14x 14x   1x   13x 1x     12x 11x   10x 10x 10x 6x     6x 6x 5x 5x   1x     4x 4x   4x 4x   7x 7x                               1x 1x         6x 6x 6x   1x 1x      
// @implements UC-SPACE-009.1, UC-SPACE-016.1
/**
 * POST /v1/flows/{flowId}/pages/{pageSlug}/publish  (`pages:update`)
 *
 * `{ publish: true }` copies the draft to the published version, which is
 * what visitors read; `{ publish: false }` removes the published version (the
 * draft stays). Images only the removed version used are deleted. Publishing
 * checks the data blocks again, for the publisher, and freezes the field list
 * of their forms (utils/spaceData.js). Links between pages must keep working
 * (UC-SPACE-016.1): a page other published pages link to can't be
 * unpublished, a page linking to an unpublished one can't be published.
 */
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
const { PAGE_SLUG_REGEX, unpublishedLinkedPages } = require('../utils/spacePages')
const { checkEntityBlocks, freezeForms, DataBlockError } = require('../utils/spaceData')
const {
  respond,
  getPage,
  listPages,
  memberAccess,
  forbidden,
  pageNotFound,
  editorView,
  deleteUnusedImages,
  refuseIfLinked
} = require('./shared')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
exports.handler = async (event) => {
  try {
    const access = await memberAccess(event)
    if (access.response) return access.response
    const { flowId, userId, canEdit } = access
    if (!canEdit) return forbidden()
 
    const pageSlug = event.pathParameters?.pageSlug
    if (typeof pageSlug !== 'string' || !PAGE_SLUG_REGEX.test(pageSlug)) return pageNotFound()
 
    let body
    try {
      body = JSON.parse(event.body || '{}')
    } catch {
      return respond(400, { error: 'Invalid JSON body' })
    }
    if (typeof body.publish !== 'boolean') {
      return respond(400, { error: 'publish must be a boolean' })
    }
 
    const page = await getPage(docClient, flowId, pageSlug)
    if (!page) return pageNotFound()
 
    const now = new Date().toISOString()
    let published = null
    if (body.publish) {
      const pages = await listPages(docClient, flowId, {
        ProjectionExpression: 'slug, published.title, draft.title'
      })
      const missing = unpublishedLinkedPages(pages, page)
      if (missing.length) return respond(409, { error: 'LINKS_TO_UNPUBLISHED', pages: missing })
      try {
        await checkEntityBlocks(docClient, access, page.draft.blocks)
      } catch (error) {
        Eif (error instanceof DataBlockError) return respond(error.statusCode, error.body)
        throw error
      }
      const blocks = await freezeForms(docClient, page.draft.blocks)
      published = { ...page.draft, blocks, publishedAt: now, publishedBy: userId }
    } else {
      const linked = await refuseIfLinked(docClient, flowId, pageSlug)
      if (linked) return linked
    }
    try {
      await docClient.send(
        new UpdateCommand({
          TableName: process.env.FLOW_PAGES_TABLE_NAME,
          Key: { flowId, slug: pageSlug },
          // The draft published is the one read: a save in between asks again
          ConditionExpression: 'updatedAt = :loaded',
          UpdateExpression: 'SET published = :published, updatedAt = :now, updatedBy = :user',
          ExpressionAttributeValues: {
            ':published': published,
            ':now': now,
            ':user': userId,
            ':loaded': page.updatedAt
          }
        })
      )
    } catch (error) {
      Eif (error.name === 'ConditionalCheckFailedException') {
        return respond(409, { error: 'PAGE_MODIFIED' })
      }
      throw error
    }
 
    const updated = { ...page, published, updatedAt: now, updatedBy: userId }
    await deleteUnusedImages(flowId, page, updated)
    return respond(200, await editorView(docClient, updated))
  } catch (error) {
    console.error('Error publishing a space page:', error)
    return respond(500, { error: 'Failed to publish page' })
  }
}