1
votes

My app uses a Firestore collection "users/{userId}/alarms/2019/10" where 2019 is the current year and 10 is the current month. I use a Cloud Firestore trigger that is called when there is a change in this collection.

At the beginning of the next month (november), I would like to monitor "users/{userId}/alarms/2019/11/{alarm}", ans so on every month. I tried the following code that I deployed with "firebase deploy --only functions".

exports.changeMonthAlarmsListener = functions.pubsub.schedule('0 0 1 * *').onRun((context) => {
    const currentDate= new Date();
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth()+1;
    console.log('new Firestore Cloud trigger for users/{user}/alarms/%d/%d/{alarm}', year, month);

    exports.monthAlarmsListener = functions.firestore
    .document('users/{user}/alarms/'+year+'/'+month+'/{alarm}')
    .onWrite((change, context) => {
        console.log('user %s: change for alarm %s', context.params.user, context.params.alarm);
    });

    return true;
});

I executed changeMonthAlarmsListener from the Cloud console. I observed the trace "new Firestore Cloud trigger for users/{user}/alarms/2019/10/{alarm}". Then I created a document "foo" in Firestore collection "users/a_user/2019/10", but it seems monthAlarmsListener is never executed since there isn't a trace "user a_user: change for alarm foo".

I guess that defining dynamically a new Cloud function is not as simple as declaring it like I do. But how to proceed ? I didn't find something in the documentation of Cloud Functions.

1

1 Answers

1
votes

Its not possible to dynamically deploy a function from within the execution of another function. If you want another function, you will have to define it statically and deploy it with the CLI. If you really need different functionality for various combinations of date parts, it sounds like you will end up making a new function for each possible combination, or just deciding withing a single function what to do with each combination every time it's invoked.