How to use the firebase-functions.database function in firebase-functions

To help you get started, we’ve selected a few firebase-functions examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github firebase / functions-samples / quickstarts / database / functions / index.js View on Github external
*
 * For more information on setting up and running this sample code, see
 * https://developers.google.com/firebase/docs/functions/writing-functions
 */

'use strict';

// [START imports]
const functions = require('firebase-functions');
// [END imports]

// [START function]
// Listen to /messages/* for writes
// Because the functions writes back to the same path that triggers onWrite,
// carefully manage infinite loops.
exports.stopShouting = functions.database().path('/messages/{childId}')
    .onWrite(event => {
      // Access the current value.
      var written = event.data.val();
      // Don't do anything (return null) if the message is not all uppercase.
      // This also prevents infinite loops.
      if (written !== written.toUpperCase()) { return null; }
      // Log this message (event.params.childId is pulled from the path)
      console.log('Shouting in the message!', event.params.childId, written);
      // Return a promise that changes the value stored
      return event.data.ref.set(written.toLowerCase());
    });
// [END function]