How to use the firebase-functions.pubsub 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 oddbit / tanam / functions / src / index.ts View on Github external
import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';

admin.initializeApp();

// noinspection JSUnusedGlobalSymbols
export const heartbeat = functions.pubsub.schedule('every 1 minutes').onRun(() => {
  console.log('lub-dub');
  return null;
});

export * from './triggers';
github jedfonner / firebase-functions-jest / pubsub-helloworld / functions / index.js View on Github external
let name = null;
    try {
      name = message.json.name;
    } catch (e) {
      console.error("PubSub message was not JSON", e);
    }
    // [END readJson]
    // Print the message in the logs.
    console.log(`Hello ${name || "World"}!`);
  });

/**
 * Cloud Function to be triggered by Pub/Sub that logs a message using the data attributes
 * published to the topic.
 */
exports.helloPubSubAttributes = functions.pubsub
  .topic("yet-another-topic-name")
  .onPublish(message => {
    // [START readAttributes]
    // Get the `name` attribute of the message.
    const name = message.attributes.name;
    // [END readAttributes]
    // Print the message in the logs.
    console.log(`Hello ${name || "World"}!`);
  });
github NUS-ALSET / achievements / functions / index.js View on Github external
exports.handleNewProblemSolution =
  // ["trigger", "both"].includes(profilesRefreshApproach) && // dev-db is paid account now
  functions.database
    .ref("/jupyterSolutionsQueue/tasks/{requestId}")
    .onWrite(change => {
      const data = change.after.val();
      return jupyterTrigger.handler(
        data,
        data.taskKey,
        data.owner,
        "handleNewProblemSolution"
      );
    });


exports.pathStatsScheduler = functions.pubsub.schedule('00 07 * * *')
  .timeZone("Asia/Singapore").
  onRun((context) => {    
    return pathStatsTrigger.handler();
  });

 
exports.handleGithubFilesFetchRequest = functions.database
  .ref("/fetchGithubFilesQueue/tasks/{requestId}")
  .onWrite(change => {
    const data = change.after.val();
    if (data) {
      return githubTrigger.handler(data, data.taskKey, data.owner);
    }
    return Promise.resolve();
  });
github doitintl / bqtop / firebase / functions / index.js View on Github external

'use strict';

// [START import]
const functions = require('firebase-functions'); // jshint ignore:line
const admin = require('firebase-admin');
admin.initializeApp();
var db = admin.database();
var refRunning = db.ref('/running-jobs');
var refFinished = db.ref('/finished-jobs');
// [END import]

// [START RunningJobsPubSub]
exports.RunningJobsPubSub = functions.pubsub.topic('bqtop-running-jobs').onPublish(message => {
        return refRunning.push(message.json);
});

// [END RunningJobsPubSub]


// [START FinishedJobsPubSub]
exports.FinishedJobsPubSub = functions.pubsub.topic('bqtop-finished-jobs').onPublish(message => {
        return refFinished.push(message.json);
});

// [END FinishedJobsPubSub]

// [START DeleteRunningJobWhenFinished]
exports.DeleteRunningJobWhenFinished = functions.database.ref('finished-jobs/{pushId}').onCreate((snapshot, context) => {
    const jobId = snapshot.val()['protoPayload']['serviceData']['jobCompletedEvent']['job']['jobName']['jobId'];
github doitintl / bqtop / firebase / functions / index.js View on Github external
admin.initializeApp();
var db = admin.database();
var refRunning = db.ref('/running-jobs');
var refFinished = db.ref('/finished-jobs');
// [END import]

// [START RunningJobsPubSub]
exports.RunningJobsPubSub = functions.pubsub.topic('bqtop-running-jobs').onPublish(message => {
        return refRunning.push(message.json);
});

// [END RunningJobsPubSub]


// [START FinishedJobsPubSub]
exports.FinishedJobsPubSub = functions.pubsub.topic('bqtop-finished-jobs').onPublish(message => {
        return refFinished.push(message.json);
});

// [END FinishedJobsPubSub]

// [START DeleteRunningJobWhenFinished]
exports.DeleteRunningJobWhenFinished = functions.database.ref('finished-jobs/{pushId}').onCreate((snapshot, context) => {
    const jobId = snapshot.val()['protoPayload']['serviceData']['jobCompletedEvent']['job']['jobName']['jobId'];
    return refRunning
        .orderByChild('protoPayload/serviceData/jobInsertResponse/resource/jobName/jobId')
        .equalTo(jobId)
        .once("value")
        .then(function (snapshot) {
            snapshot.forEach(function (childSnapshot) {
                refRunning.child(childSnapshot.key).remove();
            });
github jthegedus / firebase-gcp-examples / cron / src / functions.js View on Github external
const functions = require('firebase-functions');

exports.englishSyntax = functions.pubsub
  .schedule('every 10 minutes')
  .timeZone('Australia/NSW')
  .onRun(context => {
    console.log('triggered every 10 minutes', context);
  });

exports.cronSyntax = functions.pubsub
  .schedule('5 * * * *')
  .timeZone('Pacific/Auckland')
  .onRun(context => {
    console.log('triggered every 5 minutes', context);
  });
github faucetsdn / daq / firebase / functions / index.js View on Github external
const rundoc = port_doc.collection('runid').doc(runid);
  rundoc.collection('test').get().then(function(snapshot) {
    snapshot.forEach(function(run_test) {
      console.log('Deleting', port, runid, run_test.id);
      rundoc.collection('test').doc(run_test.id)
        .delete().catch((error) => {
          console.error('Error deleting', port, runid, run_test.id, error);
        });
    });
  });
  rundoc.delete().catch((error) => {
    console.error('Error deleting', port, runid, error);
  });
}

exports.daq_firestore = functions.pubsub.topic('daq_runner').onPublish((event) => {
  const message = event.json;
  const origin = event.attributes.origin;
  const message_type = message.type;
  const payload = message.payload;

  if (message_type === 'runner_config') {
    handle_runner_config(origin, payload);
  } else if (message_type === 'test_result') {
    handle_test_result(origin, payload);
  } else if (message_type === 'heartbeat') {
    handle_heartbeat(origin, payload);
  } else {
    throw `Unknown message type ${message_type} from ${origin}`
  }
  return null;
});
github ONEARMY / community-platform / functions / src / exports / tasks.ts View on Github external
************************************************************************************/

import * as functions from 'firebase-functions'
import DHSite from '../DaveHakkensNL'
import { BackupDatabase } from '../Firebase/databaseBackup'
import * as FirebaseSync from '../Firebase/firebaseSync'

export const weeklyTasks = functions.pubsub
  .topic('weekly-tick')
  .onPublish(async (message, context) => {
    console.log('weekly tick', message, context)
    const backupStatus = await BackupDatabase()
    console.log(backupStatus)
  })

export const dailyTasks = functions.pubsub
  .topic('daily-tick')
  .onPublish(async (message, context) => {
    console.log('daily tick', message, context)
    DHSite.updateDHUserIds()
    FirebaseSync.syncAll()
  })
github ONEARMY / community-platform / functions / src / exports / tasks.ts View on Github external
/************ Cron tasks ***********************************************************
Use pubsub to automatically subscribe to messages sent from cron.
Add/change schedule from `./functions-cron/appengine/cron.yaml`
************************************************************************************/

import * as functions from 'firebase-functions'
import DHSite from '../DaveHakkensNL'
import { BackupDatabase } from '../Firebase/databaseBackup'
import * as FirebaseSync from '../Firebase/firebaseSync'

export const weeklyTasks = functions.pubsub
  .topic('weekly-tick')
  .onPublish(async (message, context) => {
    console.log('weekly tick', message, context)
    const backupStatus = await BackupDatabase()
    console.log(backupStatus)
  })

export const dailyTasks = functions.pubsub
  .topic('daily-tick')
  .onPublish(async (message, context) => {
    console.log('daily tick', message, context)
    DHSite.updateDHUserIds()
    FirebaseSync.syncAll()
  })
github alvarowolfx / weather-station-gcp-mongoose-os / functions / index.js View on Github external
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const bigquery = require('@google-cloud/bigquery')();
const cors = require('cors')({ origin: true });

admin.initializeApp(functions.config().firebase);

const db = admin.database();

/**
 * Receive data from pubsub, then 
 * Write telemetry raw data to bigquery
 * Maintain last data on firebase realtime database
 */
exports.receiveTelemetry = functions.pubsub
  .topic('telemetry-topic')
  .onPublish((message, context) => {
    const attributes = message.attributes;
    const payload = message.json;

    const deviceId = attributes['deviceId'];

    const data = {
      humidity: payload.hum,
      temp: payload.temp,
      deviceId: deviceId,
      timestamp: context.timestamp
    };

    if (
      payload.hum < 0 ||