How to use the firebase-functions.firestore 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 / 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 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 how-to-firebase / firelist-react / functions / index.js View on Github external
/* 
  CHALLENGE Functions 06
  - Read and understand the following code carefully.
    We're using a dependency injection pattern, because our functions must be 100% testable.
    Our dependencies are the `admin` and `environment` variables which are combined into `context`. 
    Each function is a higher-order function that returns the actual function that Cloud Functions
    will run. The higher-order function takes all of the context that the inner function needs.
    So UploadsOnFinalize needs a context object that looks like { admin, environment }. 
    It can then return uploadsOnFinalize, which is the fully-initialized function that we'll
    pass to Cloud Functions with the .onFinalize method.
*/

// thumbnails-on-delete
const notesOnUpdate = NotesOnUpdate(context);
exports.notesOnUpdate = functions.firestore
  .document('notes/{noteId}')
  .onUpdate(notesOnUpdate);

// thumbnails-on-delete
const thumbnailsOnDelete = ThumbnailsOnDelete(context);
exports.thumbnailsOnDelete = functions.storage
  .object()
  .onDelete(thumbnailsOnDelete);

// thumbnails-on-finalize
const thumbnailsOnFinalize = ThumbnailsOnFinalize(context);
exports.thumbnailsOnFinalize = functions.storage
  .object()
  .onFinalize(thumbnailsOnFinalize);

// uploads-on-finalize
github nkjm / table-order / functions / index.js View on Github external
"use strict";

const functions = require('firebase-functions');
const debug = require("debug")("*");
const crypto = require("crypto");
const axios = require("axios");
const Promise = require("bluebird");

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();

// If the order status is updated from "paid" to "ready", we send ready message through LINE
exports.notify_order_ready = functions.firestore.document('/order/{order_id}').onUpdate((change, context) => {
    let order = change.after.data();
    let previous_order = change.before.data();

    if (!(order.status == "ready" && previous_order.status == "paid")){
        return Promise.resolve();
    }

    if (!order.line_user_id){
        debug("Required parameter: line_user_id not found.");
        return Promise.reject("Required parameter: line_user_id not found.");
    }

    let event = {
        type: "bot-express:push",
        to: {
            type: "user",
github 1amageek / firestore-commerce / functions / src / firestore / product / index.ts View on Github external
description: product.description,
			active: product.isAvailable,
			metadata: {
				product_path: product.path
			}
		}
		try {
			await stripe.products.create(nullFilter(data))
		} catch (error) {
			console.error(error)
			product.isAvailable = false
			await product.update()
		}
	})

export const onUpdate = functions.firestore
	.document('/commerce/{version}/products/{productID}')
	.onUpdate(async (snapshot, context) => {
		console.info(context)
		const product: Product = Product.fromSnapshot(snapshot.after)
		if (!product.isAvailable) {
			return
		}
		const STRIPE_API_KEY = config.stripe.api_key || functions.config().stripe.api_key
		if (!STRIPE_API_KEY) {
			throw new functions.https.HttpsError('invalid-argument', 'The functions requires STRIPE_API_KEY.')
		}
		const stripe = new Stripe(STRIPE_API_KEY)
		const data: Stripe.products.IProductUpdateOptions = {
			name: product.name,
			caption: product.caption,
			description: product.description,
github oddbit / tanam / firebase / entries.ts View on Github external
if (change.after.exists) {
            trxContentType.numEntries[entryAfter.status] += 1;
        }

        console.log(`Num ${entryBefore.contentType} entries after: ${JSON.stringify(trxContentType.numEntries)}`);
        trx.set(contentTypeRef, trxContentType);
    });
});

export const saveRevision = functions.firestore.document('tanam-entries/{documentId}').onUpdate((change) => {
    const entryBefore = change.before.data() as ContentEntry;
    console.log(`Saving revision ${entryBefore.revision} of ${change.before.ref.path}`);
    return change.before.ref.collection('revisions').doc(`${entryBefore.id}+${entryBefore.revision}`).set(entryBefore);
});

export const deleteRevisions = functions.firestore.document('tanam-entries/{documentId}').onDelete(async (snap) => {
    console.log(`Deleting all revisions of ${snap.ref.path}`);
    const revs = await snap.ref.collection('revisions').get();

    const promises = [];
    const batchDeletes = [];

    for (let i = 0; i < revs.docs.length; i++) {
        const doc = revs.docs[i];
        if ((i % 500) === 0) {
            batchDeletes.push(admin.firestore().batch());
        }

        const batchNum = batchDeletes.length - 1;
        console.log(`Batch delete #${batchNum} (${i + 1}/500): ${doc.id}`);
        batchDeletes[batchNum].delete(doc.ref);
    }
github duyetdev / pricetrack / functions / modules / onAddRawData.js View on Github external
const functions = require('firebase-functions')
const { collection } = require('../utils')

module.exports = functions.firestore
    .document(`${collection.URLS}/{docId}/raw/{rawId}`)
    .onWrite((change, context) => {
        console.log('triggerrr')
        console.log(change, 'change')
        console.log(context, 'context')

        return true
    })
github 1amageek / pring-admin.ts / src / base.ts View on Github external
static getTriggerDocument(): functions.firestore.DocumentBuilder {
        return functions.firestore.document(this.getTriggerPath())
    }
github stevekinney / think-piece / functions / index.js View on Github external
//
exports.helloWorld = functions.https.onRequest((request, response) => {
  response.send('Hello from Firebase!');
});

exports.getAllPosts = functions.https.onRequest(async (request, response) => {
  const snapshot = await admin
    .firestore()
    .collection('posts')
    .get();
  const posts = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));

  response.json({ posts });
});

exports.incrementCommentCount = functions.firestore
  .document('posts/{postId}/comments/{commentId}')
  .onCreate(async (snapshot, context) => {
    const { postId } = context.params;
    const postRef = firestore.doc(`posts/${postId}`);

    const snap = await postRef.get();
    const comments = snap.get('comments');

    return postRef.update({ comments: comments + 1 });
  });

exports.decrementCommentCount = functions.firestore
  .document('posts/{postId}/comments/{commentId}')
  .onDelete(async (snapshot, context) => {
    const { postId } = context.params;
    const postRef = firestore.doc(`posts/${postId}`);
github bmcmahen / julienne / functions / index.js View on Github external
const filterString = getFilterStringFromUsers(null, userIds);
    const params = {
      filters: filterString,
      userToken: req.user.user_id
    };

    const key = client.generateSecuredApiKey(ALGOLIA_SEARCH_KEY, params);
    res.json({ key });
  });
});

/**
 * Index our text on creation
 */

exports.onRecipeCreated = functions.firestore
  .document("recipes/{recipeId}")
  .onCreate(snap => {
    return indexEntry(snap);
  });

/**
 * Update our algolia index on updates
 */

exports.onRecipeUpdated = functions.firestore
  .document("recipes/{recipeId}")
  .onUpdate(snap => {
    return indexEntry(snap.after);
  });

function indexEntry(entry) {