All files / space-pages delete.js

100% Statements 28/28
100% Branches 14/14
100% Functions 1/1
100% Lines 22/22

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                2x 2x 2x               2x   2x   2x 9x 9x 9x 7x 7x   6x 6x 5x   4x 3x   2x             2x   1x 1x   1x 1x      
// @implements UC-SPACE-009.1, UC-SPACE-016.1
/**
 * DELETE /v1/flows/{flowId}/pages/{pageSlug}  (`pages:update`)
 *
 * Deletes the page, published version included, then its images; refused
 * while another published page links to it (UC-SPACE-016.1), and for the home
 * page, which the space always has (utils/spaceHome.js): 409 HOME_PAGE.
 */
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, DeleteCommand } = require('@aws-sdk/lib-dynamodb')
const { HOME_SLUG, PAGE_SLUG_REGEX } = require('../utils/spacePages')
const {
  respond,
  memberAccess,
  forbidden,
  pageNotFound,
  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, canEdit } = access
    if (!canEdit) return forbidden()
 
    const pageSlug = event.pathParameters?.pageSlug
    if (typeof pageSlug !== 'string' || !PAGE_SLUG_REGEX.test(pageSlug)) return pageNotFound()
    if (pageSlug === HOME_SLUG) return respond(409, { error: 'HOME_PAGE' })
 
    const linked = await refuseIfLinked(docClient, flowId, pageSlug)
    if (linked) return linked
 
    const result = await docClient.send(
      new DeleteCommand({
        TableName: process.env.FLOW_PAGES_TABLE_NAME,
        Key: { flowId, slug: pageSlug },
        ReturnValues: 'ALL_OLD'
      })
    )
    if (!result.Attributes) return pageNotFound()
 
    await deleteUnusedImages(flowId, result.Attributes, null)
    return { statusCode: 204, headers: { 'Access-Control-Allow-Origin': '*' }, body: '' }
  } catch (error) {
    console.error('Error deleting a space page:', error)
    return respond(500, { error: 'Failed to delete page' })
  }
}