How to use the firebase-functions.database.ref 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 TarikHuber / react-most-wanted / packages / cra-template-rmw / template / functions / db / roles / onWrite.f.js View on Github external
import { database } from 'firebase-functions'
import admin from 'firebase-admin'

export default database
  .ref('/roles/{roleUid}')
  .onWrite((eventSnap, context) => {
    // Exit when the data is not deleted.
    if (eventSnap.after.exists()) {
      return null
    }

    const roleUid = context.params.roleUid

    return admin
      .database()
      .ref(`role_grants/${roleUid}`)
      .remove()
  })
github machinelabs / machinelabs / firebase / functions / src / post-user-create.ts View on Github external
import { Change, Runnable, TriggerAnnotated } from 'firebase-functions/lib/cloud-functions';
import { DataSnapshot } from 'firebase-functions/lib/providers/database';

import { setBetaPlan } from './user/add-plan';
import { MailChimp } from './mailchimp/mailchimp';

const mailchimpConfig = config().mailchimp;
let mailchimp;

if (!mailchimpConfig) {
  console.warn('MailChimp config not set. For production make sure this is correctly configured.');
} else {
  mailchimp = new MailChimp(mailchimpConfig.api_key);
}

export const postUserCreate = database.ref('/users/{id}/common').onCreate((snap, context) => {
  const user = snap.val();
  console.log(`Subscribing user to MailChimp and adding 'beta' plan`, user);
  return Promise.all([
    mailchimp ? mailchimp.addUserToList(user, mailchimpConfig.all_users_list_id) : Promise.resolve(),
    setBetaPlan(user.id)
  ]);
});
github TarikHuber / react-most-wanted / packages / cra-template-rmw / template / functions / db / userRoles / onWrite.f.js View on Github external
import { database } from 'firebase-functions'
import admin from 'firebase-admin'

exports = module.exports = database
  .ref('/user_roles/{userUid}/{roleUid}')
  .onWrite((eventSnapshot, context) => {
    const userUid = context.params.userUid
    const roleUid = context.params.roleUid

    const roleGrantsRef = admin.database().ref(`role_grants/${roleUid}`)

    return roleGrantsRef.once('value').then(snapshot => {
      let promises = []

      snapshot.forEach(grant => {
        let grantRef = false

        console.log('User role changed:', eventSnapshot.after.val())

        if (eventSnapshot.after.val()) {
github machinelabs / machinelabs / firebase / functions / src / post-lab-write.ts View on Github external
import * as admin from 'firebase-admin';
import { database } from 'firebase-functions';

import * as crypto from 'crypto';

import { Change, Runnable, TriggerAnnotated } from 'firebase-functions/lib/cloud-functions';
import { DataSnapshot } from 'firebase-functions/lib/providers/database';

export const postLabWrite = database
  .ref('/labs/{id}/common')
  .onWrite((change, context) => Promise.all([updateIndices(change), setHasCachedRun(change, context)]));

function hashDirectory(directory) {
  const hasher = crypto.createHash('sha256');
  return hasher.update(JSON.stringify(directory)).digest('hex');
}

function updateIndices(change) {
  const delta = {};
  const data = change.after.val();

  console.log('Post lab write: updating indices');

  delta[`/idx/user_labs/${data.user_id}/${data.id}`] = true;
  delta[`/idx/user_visible_labs/${data.user_id}/${data.id}`] = data.hidden ? null : true;
github machinelabs / machinelabs / firebase / functions / src / post-handshake-write.ts View on Github external
import { database } from 'firebase-functions';
import * as admin from 'firebase-admin';

import { DataSnapshot } from 'firebase-functions/lib/providers/database';
import { Runnable, TriggerAnnotated } from 'firebase-functions/lib/cloud-functions';

export const postHandshakeCommitCreate = database.ref('/handshakes/{id}/commit/user_id').onCreate((snap, context) => {
  const userId = snap.val();
  const id = context.params.id;
  console.log(userId);
  console.log(id);
  console.log('making token');
  return admin
    .auth()
    .createCustomToken(userId)
    .catch(e => console.error(e))
    .then(token => {
      console.log('token' + token);
      return admin
        .database()
        .ref(`/handshakes/${id}/request/token`)
        .set(token);
    });
github machinelabs / machinelabs / firebase / functions / src / post-execution-write.ts View on Github external
import * as admin from 'firebase-admin';
import { database } from 'firebase-functions';

import { Change, Runnable, TriggerAnnotated } from 'firebase-functions/lib/cloud-functions';
import { DataSnapshot } from 'firebase-functions/lib/providers/database';

import { appendEntryToMonthIndex, updateUserExecutions } from './user-execution-index-tools';
import { pathify } from './util/pathify';

export const postExecutionWrite = database.ref('/executions/{id}/common').onWrite((change, context) => {
  const delta = {};
  const data = change.after.val();

  console.log(`Running post execution handler for ${data.id}`);

  updateVisibleExecutions(context, data, delta);
  updateLabExecution(context, data, delta);
  updateUserExecutions(context, data, delta);

  return admin
    .database()
    .ref(`/labs/${data.lab.id}/common`)
    .once('value')
    .then(snapshot => snapshot.val())
    .then(lab => {
      if (
github TarikHuber / react-most-wanted / packages / cra-template-rmw / template / functions / db / triggers / onCreate.f.js View on Github external
import { database } from 'firebase-functions'

export default database.ref('/triggers/{uid}').onWrite(snap => {
  return snap.after.ref.set(null)
})
github TarikHuber / react-most-wanted / packages / cra-template-rmw / template / functions / db / publicChats / onCreate.f.js View on Github external
import { database } from 'firebase-functions'
import admin from 'firebase-admin'

export default database
  .ref('/public_chats/{taskUid}')
  .onCreate((eventSnapshot, context) => {
    const authorName = eventSnapshot.child('authorName').val()
    const authorPhotoUrl = eventSnapshot.child('authorPhotoUrl').val()

    return admin
      .database()
      .ref(`/notification_tokens`)
      .once('value')
      .then(nTokens => {
        let registrationTokens = []

        nTokens.forEach(user => {
          user.forEach(token => {
            registrationTokens.push(token.key)
          })
github TarikHuber / react-most-wanted / packages / cra-template-rmw / template / functions / db / userChatMessages / onUpdate.f.js View on Github external
import { database } from 'firebase-functions'
import admin from 'firebase-admin'

export default database
  .ref('/user_chat_messages/{senderUid}/{receiverUid}/{messageUid}')
  .onUpdate((data, context) => {
    if (context.authType === 'ADMIN') {
      return null
    }

    const senderUid = context.params.senderUid
    const receiverUid = context.params.receiverUid
    const messageUid = context.params.messageUid
    const senderChatRef = admin
      .database()
      .ref(`/user_chats/${senderUid}/${receiverUid}`)
    const receiverChatRef = admin
      .database()
      .ref(`/user_chats/${receiverUid}/${senderUid}`)
    const receiverChatMessageRef = admin
github TarikHuber / react-most-wanted / packages / cra-template-rmw / template / functions / db / usersCount / onDelete.f.js View on Github external
import { database } from 'firebase-functions'
import admin from 'firebase-admin'
import moment from 'moment'
import usersUtil from 'firebase-function-tools/lib/users'

export default database.ref('/users_count').onDelete((data, context) => {
  const getDBUsers = admin
    .database()
    .ref('users')
    .once('value')
  const getAuthUsers = usersUtil.listAllUsers()

  return Promise.all([getDBUsers, getAuthUsers]).then(resulsts => {
    const dbUsers = resulsts[0]
    const authUsers = resulsts[1]
    let promises = []

    let userUids = []
    let providerCount = {}
    let usersPublicData = {}
    let usersNotificationTokens = {}