Script that inserts previous and next pages as 'teasers'

The script generates teasers for “Previous” and “Next” page entities linked to the current page. A “teaser” is a short excerpt or preview of a longer piece of content of another entity, used to give readers a glimpse of what to expect before clicking to navigate to that entity.

Features:

  • They summarize the content up to a configurable number of words.
  • The teaser titles are clickable mention links formatted as H2 headers for easy navigation, which allows to show additional fields.
  • They include a “Read more …” link that directs users to the full content on the respective page.

Use cases

This functionality is particularly useful for creating interconnected content within a workspace, such as documentation systems, knowledge bases, or project management environments where quick navigation between related pages can significantly improve information retrieval efficiency and user engagement.

Result

chrome_OFe2s5hBFy

Script

const fibery = context.getService('fibery');
const pageDb = 'YourSpaceName/Page'; // The database for Page
const TEASER_WORD_COUNT = 50; // Constant for the number of words in the teaser

// Function to fetch a page by ID and its related fields, including checks for missing fields
async function fetchPageById(pageId) {
    const page = await fibery.getEntityById(pageDb, pageId, ['Description', 'Name', 'Previous', 'Next', 'Previous Page', 'Next Page', 'Public Id']);
    if (!page.Description) {
        console.error('Description field is missing for page:', pageId);
    }
    return page;
}

// Helper function to construct a teaser from a page entity's Description
async function getTeaserContent(descriptionSecret, publicId) {
    if (!descriptionSecret) {
        return ''; // Return an empty string if the secret is undefined
    }
    const descriptionContent = await fibery.getDocumentContent(descriptionSecret, 'md');
    const teaserText = descriptionContent.split(/\s+/).slice(0, TEASER_WORD_COUNT).join(" ") + '... '; // Use TEASER_WORD_COUNT
    const readMoreLink = `[Read more ...](https://cce.fibery.io/CCE_Root/Page/${publicId})`;
    return teaserText + readMoreLink; // Append the "Read more ..." link
}

// Function to update the content of a document field
async function updateDocumentContent(documentSecret, content) {
    if (documentSecret) {
        await fibery.setDocumentContent(documentSecret, content, 'md');
    } else {
        console.error('Document secret is undefined, cannot update content');
    }
}

async function updateTeasersForCurrentPage() {
    try {
        const currentPageId = args.currentEntities[0].id;
        const currentPage = await fetchPageById(currentPageId);

        // Database ID for the 'Page' entities, used in teaser titles
        const databaseId = '8ff09230-0883-11ee-a2e3-dd72e97a05a2';

        // Update Previous Page teaser
        if (currentPage.Previous) {
            const previousPage = await fetchPageById(currentPage.Previous.Id);
            if (previousPage.Description && previousPage.Description.Secret && currentPage['Previous Page'] && currentPage['Previous Page'].Secret) {
                const previousTeaserContent = `## [[#^${databaseId}/${previousPage.Id}]]\n\n` + await getTeaserContent(previousPage.Description.Secret, previousPage['Public Id']);
                await updateDocumentContent(currentPage['Previous Page'].Secret, previousTeaserContent);
            }
        }

        // Update Next Page teaser
        if (currentPage.Next) {
            const nextPage = await fetchPageById(currentPage.Next.Id);
            if (nextPage.Description && nextPage.Description.Secret && currentPage['Next Page'] && currentPage['Next Page'].Secret) {
                const nextTeaserContent = `## [[#^${databaseId}/${nextPage.Id}]]\n\n` + await getTeaserContent(nextPage.Description.Secret, nextPage['Public Id']);
                await updateDocumentContent(currentPage['Next Page'].Secret, nextTeaserContent);
            }
        }

        console.log('Teasers updated for current Page with embedded references as H2 headers and "Read more ..." link.');
    } catch (error) {
        console.error('Error updating teasers for current Page:', error);
    }
}

await updateTeasersForCurrentPage();

Explanation

  1. Initialize Fibery Service and Set Constants:
  • The script begins by initializing the Fibery API service connection and defining essential constants such as pageDb (the database for the Page entity) and TEASER_WORD_COUNT, which determines the number of words to include in the teaser.
  1. Fetch Page Details (fetchPageById function):
  • This function retrieves detailed information for a specified page ID, including its description, name, relationships to previous and next pages, and their document fields, as well as the public ID, crucial for generating “Read more …” links.
  1. Generate Teaser Content (getTeaserContent function):
  • Extracts the description content of a page, truncates it to the defined word count for the teaser, and appends a “Read more …” link. This link is formatted to direct users to the full content of the page using its public ID, enhancing navigability within the Fibery workspace.
  1. Update Document Content (updateDocumentContent function):
  • Responsible for updating the content of specific document fields within Fibery, this function applies the new teaser content, including the mention link for the title as an H2 header and the “Read more …” link.
  1. Update Teasers for the Current Page (updateTeasersForCurrentPage function):
  • Central to the script, this function performs several key operations for the current page entity identified from args.currentEntities[0].id:
    • Retrieve Previous and Next Page Information: Fetches detailed info for linked previous and next pages.
    • Construct Teaser Content: Generates teaser content for both linked pages, incorporating their descriptions truncated to the defined word count and appending “Read more …” links.
    • Format and Update Teasers: Integrates the teaser content into mention links for titles displayed as H2 headers, then updates the “Previous Page” and “Next Page” document fields on the current page with this content.
3 Likes