Search code examples
javascriptfirebasefirebase-realtime-databasetriggersgoogle-cloud-functions

RTDB trigger for nested hierarchy


I'm trying to write an RTDB trigger that listens to a dynamic nested hierarchy in its path. Does anyone familiar with RTDB triggers know the best way to do this?

So the group hierarchy in the path can be any deep as any group can have certain metadata on them. This is what I have so far:

export const onGroupMetadataChanged = functions.database
    .ref("/mainGroup/{subGroupHierarchy}/metadata")
    .onWrite(async (change, context) => {
        const newMetadata = change.after.val();
        const groupHierarchy = context.params.subGroupHierarchy;
        await MetadataService.syncMetadataInCloudSql(
            newMetadata,
            groupHierarchy,
        );
    });

In the example above subGroupHierarchy can be of any depth so can be groups/nested-group/groups/nested-nested-group OR can be groups/nested-group/groups/nested-nested-group/groups/nested-nested-nested-group

Obviously, I'm trying to avoid writing a trigger for every possible route

Is this possible to do?


Solution

  • There is no syntax to match an unknown number of levels in Realtime Database triggers for Cloud Functions. The best I can think of is to trigger at the highest common level, and then figure out whether the trigger contains data you need to process in your function code.

    In general this multi-level nesting is an anti-pattern in Realtime Database, so I recommend reading up in the documentation on structuring data, specifically the sections on avoiding overly nesting data and keeping data flat.

    For a nested group structure like yours, I'd typically end up with a flat list of all groups, where each group has a property with the ID of its parent group - similar to what you'd end up with in a relational data model for it too.