How to use firebase-functions - 10 common examples

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 / firebase-tools / scripts / triggers-end-to-end-tests / functions / index.js View on Github external
exports.writeToRtdb = functions.https.onRequest(async (req, res) => {
  const ref = admin.database().ref(START_DOCUMENT_NAME);
  await ref.set({ start: new Date().toISOString() });
  ref.once("value", (snap) => {
    res.json({ data: snap });
  });
});

exports.writeToPubsub = functions.https.onRequest(async (req, res) => {
  const msg = await pubsub.topic(PUBSUB_TOPIC).publishJSON({ foo: "bar" }, { attr: "val" });
  console.log("PubSub Emulator Host", process.env.PUBSUB_EMULATOR_HOST);
  console.log("Wrote PubSub Message", msg);
  res.json({ published: "ok" });
});

exports.firestoreReaction = functions.firestore
  .document(START_DOCUMENT_NAME)
  .onWrite(async (/* change, ctx */) => {
    console.log(FIRESTORE_FUNCTION_LOG);
    /*
     * Write back a completion timestamp to the firestore emulator. The test
     * driver program checks for this by querying the firestore emulator
     * directly.
     */
    const ref = admin.firestore().doc(END_DOCUMENT_NAME + "_from_firestore");
    await ref.set({ done: new Date().toISOString() });

    /*
     * Write a completion marker to the firestore emulator. This exercise
     * cross-emulator communication.
     */
    const dbref = admin.database().ref(END_DOCUMENT_NAME + "_from_firestore");
github prescottprue / fireadmin / functions / src / testRunner / index.js View on Github external
import * as functions from 'firebase-functions'
import Mocha from 'mocha'
import path from 'path'

export default functions.onCall.onRequest((req, res) => {
  // Add each .js file to the mocha instance
  // fs.readdirSync(testDir).filter(function(file){
  //     // Only keep the .js files
  //     return file.substr(-3) === '.js';
  //
  // }).forEach(function(file){
  //     mocha.addFile(
  //         path.join(testDir, file)
  //     );
  // });
  const mocha = new Mocha({
    useColors: true
  })
  mocha.addFile(path.join(__dirname, './some.js'))
  mocha.run(failures => {
    console.log('failed:', failures)
github oddbit / tanam / functions / src / triggers / storage.ts View on Github external
fileType: 'image',
  };

  return await Promise.all([
    firestoreRef.set(tanamFile),
    bucket.file(storageObject.name).delete(),
    bucket.file(tanamFile.filePath).save(originalFileBuffer, storageObject.metadata),
    bucket.file(tanamFile.variants.small).save(await resizeAndConvertImage(300), metadata),
    bucket.file(tanamFile.variants.medium).save(await resizeAndConvertImage(800), metadata),
    bucket.file(tanamFile.variants.large).save(await resizeAndConvertImage(1600), metadata),
  ]);
});


// noinspection JSUnusedGlobalSymbols
export const onThemeAssetsFileUpload = functions.storage.object().onFinalize(async (storageObject) => {
  const regexNameMatch = storageObject.name.match(/^\/?tanam\/(.*)\/themes\//);

  if (!regexNameMatch) {
    console.log(`Not an upload asset file task: ${storageObject.name} (${storageObject.contentType})`);
    return null;
  }
  console.log('[UploadAssetFiles]' + JSON.stringify(storageObject));
  const objectNameArr = storageObject.name.split('/');
  const themeId = objectNameArr[3];

  const siteId = regexNameMatch[1];
  const fileId = SHA1(storageObject.name).toString().toLowerCase();

  const fileRef = admin.firestore()
    .collection('tanam').doc(siteId)
    .collection('themes').doc(themeId)
github rostag / bigpolicy_eu / fbs / functions / server / mongo / database.js View on Github external
const mongoose = require('mongoose');

// FIXME
const firebase = require('firebase/app');
const admin = require('firebase-admin');
// Initialize Firebase
console.log('Firebase config:', process, process.env, process.env.FIREBASE_CONFIG, JSON.parse(process.env.FIREBASE_CONFIG));
firebase.initializeApp(JSON.parse(process.env.FIREBASE_CONFIG));
// END FIXME

// Firebase environment adopted:
const functions = require('firebase-functions');
const MONGO_URI = functions && functions.config() && functions.config().mongo && functions.config().mongo.uri ||
  'mongodb://localhost:27027/bigpolicy';

mongoose.Promise = global.Promise;

var options = {
  poolSize: 5,
  native_parser: true,
  useNewUrlParser: true
};

try {
  console.log('Mongo connected:' + MONGO_URI);
  mongoose.connect(MONGO_URI, options);
} catch (err) {
  console.error('Mongo connection failed: ', err);
}
github ccckmit / ccckmit / course / webProgramming / example / database / firebase / friendlychat-web / cloud-functions / functions / index.js View on Github external
* You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Import the Firebase SDK for Google Cloud Functions.
const functions = require('firebase-functions');
// Import and initialize the Firebase Admin SDK.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const gcs = require('@google-cloud/storage')();
const Vision = require('@google-cloud/vision');
const vision = new Vision();
const spawn = require('child-process-promise').spawn;
const path = require('path');
const os = require('os');
const fs = require('fs');

// Adds a message that welcomes new users into the chat.
exports.addWelcomeMessages = functions.auth.user().onCreate(event => {
  const user = event.data;
  console.log('A new user signed in for the first time.');
  const fullName = user.displayName || 'Anonymous';

  // Saves the new welcome message into the database
  // which then displays it in the FriendlyChat clients.
github prescottprue / fireadmin / functions / index.js View on Github external
const glob = require('glob')
const path = require('path')
const admin = require('firebase-admin')
const functions = require('firebase-functions')
const initializeFireadminLib = require('@fireadmin/core').initialize
const getEnvConfig = require('./dist/utils/firebaseFunctions').getEnvConfig

// Initialize Firebase so it is available within functions
try {
  admin.initializeApp(functions.config().firebase)
} catch (e) {
  /* istanbul ignore next: not called in tests */
  console.error(
    'Caught error initializing app with functions.config():',
    e.message || e
  )
}
try {
  const serviceAccount = getEnvConfig('service_account')
  const fireadminApp = admin.initializeApp(
    {
      credential: admin.credential.cert(serviceAccount),
      databaseURL: `https://${serviceAccount.project_id}.firebaseio.com`
    },
    'withServiceAccount'
  )
github duyetdev / pricetrack / functions / modules / onNewUser.js View on Github external
const functions = require('firebase-functions')
const mailTransport = require('../utils/nodemailer')
const { email: { APP_NAME, FROM_EMAIL } } = require('../utils/constants')

const { db, collection } = require('../utils')

const ADMIN_EMAIL = functions.config().pricetrack.admin_email || ''

module.exports = functions.auth.user().onCreate(async user => {
    const email = user.email
    const displayName = user.displayName

    // Update user info to DB
    try {
        let doc = db.collection(collection.USER).doc(email)
        doc.set(JSON.parse(JSON.stringify(user)), { merge: true })
    } catch (e) {
        console.error(e)
    }

    const mailOptions = {
        from: `${APP_NAME} <${FROM_EMAIL}>`,
        to: ADMIN_EMAIL,
github frinder / frinder-app / cloudfunctions / functions / index.js View on Github external
var geoFire = new GeoFire(dbRef);

      //var key = event.params.test;
      var location = [newLat, newLon];

      geoFire.set(userId, location).then(() => {
         console.log('GeoFire Update successful for ' + userName + '(' + userId + ')');
      }).catch(error => {
         console.log(error);
      });
    }

    return true;
});

exports.createUser = functions.firestore
  .document('users/{userId}')
  .onCreate(event => {
    // Get an object representing the document
    var value = event.data.data();

    var userName = value.name;
    var userId = value.id;
    var lat = value.location[0];
    var lon = value.location[1];

    //add value to GeoFire

    // Create a Firebase reference where GeoFire will store its information
    var dbRef = admin.database().ref('/users_location');

    // Create a GeoFire index
github TarikHuber / react-most-wanted / packages / cra-template-rmw / template / functions / auth / onCreate.f.js View on Github external
import admin from 'firebase-admin'
import moment from 'moment'
import nodemailer from 'nodemailer'

const gmailEmail = encodeURIComponent(
  functions.config().gmail ? functions.config().gmail.email : ''
)
const gmailPassword = encodeURIComponent(
  functions.config().gmail ? functions.config().gmail.password : ''
)

const mailTransport = nodemailer.createTransport(
  `smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`
)

export default functions.auth.user().onCreate((uRecord, context) => {
  const userRecord = uRecord || {}
  const email = userRecord.email // The email of the user.
  const displayName = userRecord.displayName // The display name of the user.
  const creationTime = moment(userRecord.creationTime)
  const year = creationTime.format('YYYY')
  const month = creationTime.format('MM')
  const day = creationTime.format('DD')

  return admin
    .auth()
    .getUser(userRecord.uid)
    .then(user => {
      // User  without provider data
      console.log('Event user data', userRecord)

      // User with provider data
github firebase / functions-samples / convert-images / functions / index.js View on Github external
const mkdirp = require('mkdirp-promise');
const spawn = require('child-process-promise').spawn;
const path = require('path');
const os = require('os');
const fs = require('fs');

admin.initializeApp();

// File extension for the created JPEG files.
const JPEG_EXTENSION = '.jpg';

/**
 * When an image is uploaded in the Storage bucket it is converted to JPEG automatically using
 * ImageMagick.
 */
exports.imageToJPG = functions.storage.object().onFinalize(async (object) => {
  const filePath = object.name;
  const baseFileName = path.basename(filePath, path.extname(filePath));
  const fileDir = path.dirname(filePath);
  const JPEGFilePath = path.normalize(path.format({dir: fileDir, name: baseFileName, ext: JPEG_EXTENSION}));
  const tempLocalFile = path.join(os.tmpdir(), filePath);
  const tempLocalDir = path.dirname(tempLocalFile);
  const tempLocalJPEGFile = path.join(os.tmpdir(), JPEGFilePath);

  // Exit if this is triggered on a file that is not an image.
  if (!object.contentType.startsWith('image/')) {
    console.log('This is not an image.');
    return null;
  }

  // Exit if the image is already a JPEG.
  if (object.contentType.startsWith('image/jpeg')) {