Thursday, 1 June 2017

Rewrite trigger to cron job

I return to this question.

I took the code from the Firebase example "Limit number of child nodes"

I have the following structure. Each user has his own data.

---+ root_child
   |
   +---+ Gy7FXRbRjDfAKWu7a95NgiGIZUk1  (Firebase User Id)
       |
       |
       +---+ KlNlb71qtQUXIGA4cNa (random key, generated by Firebase)
       |   |
       |   +--- (data field ...)
       |
       |
       +---+ KlNlcmfMTDjxQ0BwW1K
       |   |
       |   +--- (data field ...)
       |
       +---+ (...)

I've made some changes to the source code, but I do not know where to move next.

Here in the beginning you see my code, and then the code from the example. As you can see, I'm not an expert at nodejs.

// Max number of lines
const MAX_RECORD_COUNT = 5;
const FB_ROOT_REFERENCE = '/locations';
// Removes siblings of the node that element that triggered the function if there are more than MAX_RECORD_COUNT.
// In this example we'll keep the max number of chat message history to MAX_RECORD_COUNT.
exports.truncate = functions.https.onRequest((req, res) => {

    const cron_key = req.query.key;

    // Exit if the keys don't match
      if (!secureCompare(cron_key, functions.config().cron.key)) {
        console.log('The cron_key provided in the request does not match the cron_key set in the environment. Check that', cron_key,
            'matches the cron.key attribute in `firebase env:get`');
        res.status(403).send('Security cron_key does not match. Make sure your cron_key URL query parameter matches the ' +
            'cron.key environment variable.');
        return;
      }

//
// What should I write next?
// 

//functions.database.ref(FB_ROOT_REFERENCE + '/{messageid}').onWrite(event => {
  const parentRef = event.data.ref.parent;
  return parentRef.once('value').then(snapshot => {
    if (snapshot.numChildren() >= MAX_RECORD_COUNT) {
      let childCount = 0;
      const updates = {};
      snapshot.forEach(function(child) {
        if (++childCount <= snapshot.numChildren() - MAX_RECORD_COUNT) {
          updates[child.key] = null;
        }
      });
      // Update the parent. This effectively removes the extra children.
      return parentRef.update(updates);
    }
  });
});

I would be very grateful if anyone could help me to rewrite the trigger into a "normal" function. Thank you.



via tim4dev

No comments:

Post a Comment