fibery.createEntity Error in script when Merging rich text fields

I want to merge rich text fields into one rich text field of a new entity.

Error in script: [Error: createEntity: Cannot parse value for Yuri/Description field in ‘Yuri/Y Blocks Page’ database.
Cause: Invalid uuid 'Rich text of Y Block A
Rich text of Y Block B
'.]

In that error the ‘Rich text of Y Block A Rich text of Y Block B’ is indeed the merged text, but it expects a uuid instead.

How to solve this?

Here is the script:

const fibery = context.getService('fibery');
const utils = context.getService('utils'); // Util service for UUID generation
const yBlocksPageType = 'Yuri/Y Blocks Page'; // Replace with your actual space and type name

async function createYPageWithMergedDescriptions() {
  try {
    const currentEntity = args.currentEntities[0];
    const yBlocksPageEntity = await fibery.getEntityById(yBlocksPageType, currentEntity.id, ['Y Blocks']);
    const yBlocksEntities = yBlocksPageEntity['Y Blocks'] || [];

    let mergedDescription = ''; // Empty string to hold the merged description

    for (const yBlock of yBlocksEntities) {
      const yBlockEntity = await fibery.getEntityById('Yuri/Y Block', yBlock.Id, ['Description']);
      const richTextContent = await fibery.getDocumentContent(yBlockEntity['Description'].secret, 'md'); // Extract rich text content from each Y Block
      mergedDescription += richTextContent + '\n'; // Concatenating the rich text with a newline
    }

    const timestamp = new Date().toISOString();

    // Create the Y Page entity with the document secret
    const newYPageEntity = await fibery.createEntity(yBlocksPageType, {
      'Name': `Merge ${timestamp}`, // Set the name of the Y Page
      'Description': mergedDescription // Set the merged description as the value
    });

    console.log('New Y Page entity created:', newYPageEntity);
  } catch (error) {
    console.error('Error in script:', error);
  }
}

await createYPageWithMergedDescriptions();

The provided script aims to perform the following tasks:

  • It retrieves a specific entity and its related entities in the Fibery workspace.
    • The entity type is ‘Yuri/Y Blocks Page’, and the specific entity is identified by currentEntity.id.
    • The related entities are retrieved through the ‘Y Blocks’ relation field.
  • For each related ‘Y Block’ entity, it performs the following steps:
    • Retrieves the ‘Y Block’ entity details, specifically the ‘Description’ field which is a rich text field.
    • Retrieves the content of the ‘Description’ field using the getDocumentContent method and the document secret.
    • Appends the retrieved content to a string, mergedDescription, which is initialized as an empty string.
  • After processing all related ‘Y Block’ entities, it creates a new ‘Y Blocks Page’ entity:
    • The ‘Name’ field of the new entity is set as ‘Merge’ followed by the current timestamp.
    • The ‘Description’ field is set as the mergedDescription string.
  • Finally, it logs the details of the newly created ‘Y Blocks Page’ entity.

You can’t create an entity and populate its Description field using this syntax.
You need to create the new entity, then find the secret for its Description field and use setDocumentContent

1 Like

Thank you @Chr1sG ! :sunglasses: :partying_face: :partying_face: :partying_face:
That helped me create a working script.

For who is interested, this is the working script:

const fibery = context.getService('fibery');
const yBlocksPageType = 'Yuri/Y Blocks Page'; // Replace with your actual space and type name for Y Blocks Page
const yPageType = 'Yuri/Y Page'; // Replace with your actual space and type name for Y Page

async function updateDescription() {
    try {
        const currentEntity = args.currentEntities[0];
        const yBlocksPageEntity = await fibery.getEntityById(yBlocksPageType, currentEntity.id, ['Y Blocks']);
        const yBlocksEntities = yBlocksPageEntity['Y Blocks'] || [];

        const descriptionDocuments = await Promise.all(
            yBlocksEntities.map(async (yBlock) => {
                const yBlockEntity = await fibery.getEntityById('Y Block', yBlock.Id, ['Description']);
                return await fibery.getDocumentContent(yBlockEntity['Description'].secret, 'md');
            })
        );

        const mergedDescription = descriptionDocuments.join('\n');

        const newYPageEntity = await fibery.createEntity(yPageType, {
            'Name': `Merge ${new Date().toISOString()}`, // Set the name of the Y Page
        });

        const descriptionSecret = newYPageEntity['Description'].secret;

        await fibery.setDocumentContent(descriptionSecret, mergedDescription, 'md');

        console.log('New Y Page entity created:', newYPageEntity);
    } catch (error) {
        console.error('Error in script:', error);
    }
}

await updateDescription();

For who wants to understand the script, here is an explanation:

This script retrieves descriptions from multiple ‘Y Block’ entities within a ‘Y Blocks Page’, merges them, and then creates a new ‘Y Page’ entity in Fibery with the aggregated description.

  1. Fibery Service Initialization:
  • const fibery = context.getService('fibery');: Initializes a connection to the Fibery service, allowing the script to interact with the Fibery API.
  1. Entity Type Definitions:
  • const yBlocksPageType = 'Yuri/Y Blocks Page';: Defines a constant for the entity type ‘Y Blocks Page’. This is used to specify the type of entity from which the script will retrieve data.
  • const yPageType = 'Yuri/Y Page';: Defines a constant for the entity type ‘Y Page’. This is used to specify the type of entity the script will create.
  1. Asynchronous Function - updateDescription:
  • async function updateDescription() { ... }: Declares an asynchronous function named updateDescription. Being asynchronous allows the function to perform non-blocking operations, particularly useful for API calls.
  1. Error Handling with Try-Catch:
  • The try-catch block in the function is used for error handling. If an error occurs anywhere within the try block, execution is passed to the catch block, logging the error.
  1. Retrieving the Current Entity Context:
  • const currentEntity = args.currentEntities[0];: Extracts the first entity from args.currentEntities, which is assumed to be provided to the script in its execution context. This represents the current entity in focus.
  1. Fetching ‘Y Blocks Page’ Entity and Related ‘Y Blocks’:
  • const yBlocksPageEntity = await fibery.getEntityById(yBlocksPageType, currentEntity.id, ['Y Blocks']);: Performs an asynchronous API call to retrieve the ‘Y Blocks Page’ entity by its ID. It also fetches related ‘Y Blocks’ entities.
  • const yBlocksEntities = yBlocksPageEntity['Y Blocks'] || [];: Extracts the ‘Y Blocks’ related entities, defaulting to an empty array if none are found.
  1. Merging Descriptions from ‘Y Blocks’:
  • await Promise.all(...): Uses Promise.all to handle multiple asynchronous operations concurrently. It maps over yBlocksEntities, performing operations on each.
  • Inside the map, each ‘Y Block’ entity’s description is fetched and returned. This is achieved by another API call fibery.getEntityById for each ‘Y Block’, followed by fibery.getDocumentContent to get the actual description content in Markdown format ('md').
  1. Creating New ‘Y Page’ Entity:
  • const newYPageEntity = await fibery.createEntity(yPageType, {...});: Creates a new entity of type ‘Y Page’. The await ensures the script pauses until this asynchronous operation completes. The new entity’s name is set using the current date and time.
  1. Updating Description of the New ‘Y Page’ Entity:
  • const descriptionSecret = newYPageEntity['Description'].secret;: Extracts the secret key for the ‘Description’ field of the new entity.
  • await fibery.setDocumentContent(descriptionSecret, mergedDescription, 'md');: Updates the ‘Description’ field of the new ‘Y Page’ entity with the merged content.
  1. Console Logging for Debugging and Confirmation:
  • console.log('New Y Page entity created:', newYPageEntity);: Logs the details of the newly created ‘Y Page’ entity to the console. This is useful for debugging and confirming the successful creation of the entity.
  1. Execution of updateDescription Function:
  • await updateDescription();: Executes the updateDescription function. The await keyword here ensures that the script waits for the completion of updateDescription, which is crucial since updateDescription involves several asynchronous operations.
1 Like