Update a linked Document by prepending the contents of Rich Text fields

This is a Button script for a “Meeting Notes” entity to be run when the meeting ends. It takes the meeting entity’s Rich Text content (agenda, notes, etc) and prepends it to a “collected meeting notes” Document that is linked in the entity.

The idea is to make the Document into a running history of all meetings, to make it easier to search through all meetings notes.

// Retrieve the contents of some Rich Text fields from the current entity
// and prepend it to a linked Document.

const fibery = context.getService('fibery')
const fmt = 'md'   // Rich Text format

for (const entity of args.currentEntities) {
    // Get the entity's Documents collection
    const entity2 = await fibery.getEntityById( entity.type, entity.id, ['Documents'] )

    // Find the specific doc we're looking for
    const destDoc = entity2['Documents'].find( d => d.Name.match(/collected/i) )
    assert( destDoc, 'I did not find the "Collected Meeting Notes" Document' )

    // Get the document's current content
    const destDoc_Secret = await getDocumentSecret( destDoc.id )
    const oldContent = await fibery.getDocumentContent( destDoc_Secret, fmt )

    // Get the source entity's Rich Text fields content
    const newContent =
        await getRichTextContent(entity, 'Description', fmt) + '\n\n' +
        await getRichTextContent(entity, 'Next Meeting', fmt)

    // Update the doc by prepending the content from the Rich Text fields
    const header = `**——————————————————————————————————**\n\n# ${entity.Name}\n\n`
    const text = header + newContent + '\n\n' + oldContent
    await fibery.setDocumentContent( destDoc_Secret, text, fmt )

async function getRichTextContent( entity, fieldName, fmt ) {
    const secret = entity[fieldName].Secret
    return await fibery.getDocumentContent(secret, fmt)

async function getDocumentSecret( docId ) {
    const view = await fibery.getEntityById( 'fibery/view', docId, ['fibery/meta'] );
    return view['fibery/meta']['documentSecret'];

function assert(b, msg) {
    if( !b ) throw new Error(msg)