All files / space-pages public-get.js

100% Statements 25/25
100% Branches 12/12
100% Functions 2/2
100% Lines 20/20

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 9x   2x 27x 27x 27x   26x 25x   20x 20x 17x   15x 10x     5x         1x 1x      
// @implements UC-SPACE-010.1, UC-SPACE-019.1
/**
 * GET /v1/spaces/{slug}/pages/{pageSlug} (public, no authentication)
 * GET /v1/spaces/{slug}/pages/{pageSlug}/blocks/{blockId}?offset= : the next
 *   items of one of its item lists ("load more")
 *
 * A published page of a published space, visible to everyone. A draft-only
 * or unknown page gives the same 404 as an unknown space; a published
 * members-only page gives 403 MEMBERS_ONLY, without any of its content, so the
 * visitor can be offered to sign in or join. A member's browser reads
 * members-only pages through GET /v1/flows/{flowId}/pages/{pageSlug}.
 * Cached a minute by the spaces CDN (shared.js PUBLIC_CACHE_CONTROL).
 */
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb')
const { PAGE_SLUG_REGEX } = require('../utils/spacePages')
const {
  respondPublic,
  getPage,
  loadSpaceFlow,
  readableVersion,
  publishedBlockItems
} = require('./shared')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
const notFound = () => respondPublic(404, { error: 'Page not found' })
 
exports.handler = async (event) => {
  try {
    const pageSlug = event.pathParameters?.pageSlug
    if (typeof pageSlug !== 'string' || !PAGE_SLUG_REGEX.test(pageSlug)) return notFound()
 
    const flow = await loadSpaceFlow(docClient, event.pathParameters?.slug)
    if (!flow) return notFound()
 
    const page = await getPage(docClient, flow.id, pageSlug)
    if (!page?.published) return notFound()
    if (page.visibility !== 'everyone') return respondPublic(403, { error: 'MEMBERS_ONLY' })
 
    if (event.pathParameters?.blockId !== undefined) {
      return await publishedBlockItems(docClient, event, page.published, flow.id, respondPublic)
    }
 
    return respondPublic(200, {
      slug: page.slug,
      ...(await readableVersion(docClient, page.published, flow.id))
    })
  } catch (error) {
    console.error('Error getting a space page:', error)
    return respondPublic(500, { error: 'Failed to get page' })
  }
}