All files / utils spaceHome.js

96.96% Statements 32/33
90% Branches 18/20
100% Functions 8/8
100% Lines 29/29

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                  2x 2x       12x 5x 2x 5x         5x       10x   9x         6x 6x 6x 6x 6x 4x       5x       6x 6x                             3x 3x 3x 3x 3x 3x                                       1x   2x 1x   2x       2x  
// @implements UC-SPACE-009.1
/**
 * The home page a space gets when it is published without one: the same
 * content as the fixed home layout it replaces (the flow's description, then
 * the join button, which shows "Open in Flows" to a member), published at
 * once, so visitors see no change and the editors have a page to start from.
 * The home page can't be deleted nor renamed afterwards (space-pages/put.js,
 * delete.js): the space always has one.
 */
const { PutCommand } = require('@aws-sdk/lib-dynamodb')
const { HOME_SLUG, validatePageInput } = require('./spacePages')
 
/** A name or description, plain or per language, as `{ lang: text }` */
function localized(value, defaultLanguage) {
  if (typeof value === 'string') return value.trim() ? { [defaultLanguage]: value } : {}
  if (!value || typeof value !== 'object') return {}
  return Object.fromEntries(
    Object.entries(value).filter(([, text]) => typeof text === 'string' && text.trim())
  )
}
 
/** A plain text as a rich text document, one paragraph per line */
const richTextOf = (text) => ({
  type: 'doc',
  content: text
    .split('\n')
    .map((line) => line.trim())
    .filter(Boolean)
    .map((line) => ({ type: 'paragraph', content: [{ type: 'text', text: line }] }))
})
 
/** The page's input, as an editor would send it */
function homePageInput(flow) {
  const defaultLanguage = flow.defaultLanguage || 'en'
  const title = localized(flow.name, defaultLanguage)
  const description = localized(flow.description, defaultLanguage)
  const blocks = []
  if (Object.keys(description).length) {
    blocks.push({
      id: 'description',
      type: 'richText',
      content: Object.fromEntries(
        Object.entries(description).map(([lang, text]) => [lang, richTextOf(text)])
      )
    })
  }
  blocks.push({ id: 'join', type: 'join' })
  return {
    title: Object.keys(title).length ? title : { [defaultLanguage]: 'Home' },
    blocks,
    visibility: 'everyone',
    showInMenu: true,
    menuOrder: 0
  }
}
 
/**
 * Creates the published home page of the flow's space, unless it has one.
 * Best effort: the space settings are saved already, a failure is only logged.
 * @returns {Promise<boolean>} whether the page was created
 */
async function ensureHomePage(docClient, flow, userId) {
  try {
    const input = validatePageInput(homePageInput(flow), flow.id)
    Iif (!input.valid) throw new Error(`Invalid home page: ${input.error}`)
    const { draft, visibility, showInMenu, menuOrder } = input.value
    const now = new Date().toISOString()
    await docClient.send(
      new PutCommand({
        TableName: process.env.FLOW_PAGES_TABLE_NAME,
        Item: {
          flowId: flow.id,
          slug: HOME_SLUG,
          visibility,
          showInMenu,
          menuOrder,
          draft,
          published: { ...draft, publishedAt: now, publishedBy: userId },
          createdAt: now,
          createdBy: userId,
          updatedAt: now,
          updatedBy: userId
        },
        // The home page made by an editor stays as it is
        ConditionExpression: 'attribute_not_exists(slug)'
      })
    )
    return true
  } catch (error) {
    if (error.name !== 'ConditionalCheckFailedException') {
      console.error('Failed to create the home page of the space:', error)
    }
    return false
  }
}
 
module.exports = { ensureHomePage, homePageInput }