Coder Social home page Coder Social logo

firebase / functions-samples Goto Github PK

View Code? Open in Web Editor NEW
12.0K 371.0 3.8K 7.62 MB

Collection of sample apps showcasing popular use cases using Cloud Functions for Firebase

Home Page: https://firebase.google.com/docs/functions

License: Apache License 2.0

JavaScript 65.14% CSS 4.28% HTML 17.56% TypeScript 0.80% Handlebars 0.48% Python 11.75%
faas faas-platform firebase google google-cloud-platform google-cloud-functions google-cloud-storage serverless

functions-samples's Introduction

Cloud Functions for Firebase Sample Library

This repository contains a collection of samples showcasing some typical uses of Cloud Functions for Firebase.

Samples are available for the Node (2nd gen), Python (2nd gen), and Node (1st gen).

Note: Python support in Cloud Functions for Firebase is a public preview. This means that the functionality might change in backward-incompatible ways. A preview release is not subject to any SLA or deprecation policy and may receive limited or no support.

What's Cloud Functions for Firebase?

Cloud Functions is a hosted, private, and scalable Node.js environment where you can run JavaScript or Python code. Cloud Functions for Firebase integrates the Firebase platform by letting you write code that responds to events and invokes functionality exposed by other Firebase features.

Prerequisites

All samples require the Blaze pay-as-you-go billing plan to deploy. Learn more about pricing.

To learn how to get started with Cloud Functions for Firebase by having a look at the Getting Started Guide, trying the quickstart samples and looking at the documentation.

Quickstarts

Minimal samples for each Cloud Functions trigger type.

Quickstart: Uppercaser for Firestore

This quickstart sample demonstrates using Cloud Functions triggered by Firestore events. The function transforms message text written to Firestore to uppercase.

Quickstart: Add numbers and sanitize text with callable functions

HTTPS trigger quickstart: Time Server

This quickstart sample demonstrates using Cloud Functions triggered by HTTPS requests. The function returns the current server time and allows for date time formatting.

Quickstart: Uppercaser for Realtime Database

This quickstart sample demonstrates using Cloud Functions triggered by Realtime Database events. The function transforms message text written to Realtime Database to uppercase.

Hosting triggered HTTPS function quickstart: Big Ben

This quickstart demonstrates using Cloud Functions with an HTTPS trigger that's triggered through a Firebase Hosting URL. The function will display a repeated number of "BONG"s depending on the hour of the day.

Cloud Storage trigger quickstart: Thumbnail generator

This quickstart sample demonstrates using Cloud Functions triggered by Firebase Storage events. The function generates a thumbnail of uploaded images.

Auth trigger quickstart: Welcome Email

Auth user create and delete triggers aren't yet supported by 2nd gen functions

This quickstart sample demonstrates using Cloud Functions triggered by Firebase Auth events. The function sends a Welcome Email when user accounts are created (or when users sign-in using an Identity Provider for the first time) and sends a Goodbye Email when user accounts are deleted.

Auth blocking trigger quickstart: Validate and check user status

This quickstart demonstrates using Auth blocking functions to validate a user's email before they are allowed to sign in, and to see if a user is part of a list of banned users in Firestore.

PubSub trigger quickstart: Hello World

This quickstart sample demonstrates using Cloud Functions triggered by PubSub events. The functions log the PubSub payload in a Hello world message.

Test Lab trigger quickstart: Log when a matrix completes

Firebase Alerts trigger quickstart: Send crash reports to Discord](/2nd-gen/alerts-to-discord/)

Trigger a function based on a Firebase Alert, and send information about the alert to a channel in a Discord server.

Custom Events: Save image metadata

Learn how to trigger a function based on an event sent by an extension

Unit testing

Development Boilerplates

The Firebase CLI generates sample code for Cloud Functions using JavaScript or TypeScript.

Server-side generated pages w/ Handlebars templating and user sessions

This sample shows how to serve server-side generated HTML pages using the HandlebarsJs templating system and serve user-specific content by always passing the Firebase ID token in a __session cookie.

Image Processing

Here are a few samples that show how you can process or analyze images using Cloud Functions.

Image Maker

This sample demonstrates how to create various customized images such as sparkline or sphere charts through Cloud Functions and Hosting and serve it to the client. Uses an HTTP trigger.

Convert images after upload

Demonstrates how to automatically convert images that are uploaded to Firebase Storage to JPEG using ImageMagick. Uses a Firebase Storage trigger.

Moderate offensive images

Demonstrates how to automatically moderate offensive images that are uploaded to Firebase Storage by using the Google Cloud Vision API to detect offensive images and ImageMagick to blur these images. Uses a Firebase Storage trigger.

Extract image metadata

Demonstrates how to automatically extract image's metadata using ImageMagick for images that are uploaded to Firebase Storage. Uses a Firebase Storage trigger.

Task Queues: back up images from an API

See how to use Task Queues to meter traffic to a rate-limited API.

Firebase Realtime Database Data Consistency

These samples show how to implement automatic data consistency such as keeping a count of children, having a max amount of node childs, cleaning up old data etc...

LastModified Firebase Realtime Database tracking

Tracking when the Firebase Database (or a subset) was last modified. Uses a Realtime Database trigger.

Firebase Database child nodes count

Keeps track of the number of child nodes of a Firebase Database element allowing clients to filter or order results using the child count. This can be useful to keep track of the number of "likes" or "followers" of something shared through social media. Uses a Realtime Database trigger.

Limit number of child nodes

Makes sure that the number of child nodes stays below a certain threshold. This can be useful to limit the number of lines of logs or chat history below a given number. Uses a Realtime Database trigger.

Removing old items from a list

This sample shows how to remove child nodes older than 2 hours from a Firebase Database list. This can be useful for removing outdated items from a collection. Uses a Realtime Database trigger.

Solve other common use cases

Send FCM notifications

This sample demonstrates how to send a Firebase Cloud Messaging (FCM) notification from a Realtime Database triggered Function when users get new followers. The sample also features a Web UI to experience the FCM notification. Uses a Realtime Database trigger.

Google Assistant says ordinal of given number

This sample shows how to create an action for the Google Home/Assistant using the Actions SDK hosted on Cloud Functions. The sample action asks users to say a number and reads out the ordinal of that number. Uses an HTTP trigger.

Authenticated JSON API

This sample shows how to authenticate access to a JSON API to only allow access to data for a specific Firebase user. Uses an HTTP trigger.

Authorized HTTP endpoint

This sample shows how to restrict an HTTPS Function to only the Firebase users of your app. Only users who pass a valid Firebase ID token as a Bearer token in the Authorization header of the HTTP request or in a __session cookie are authorized to use the function. Checking the ID token is done with an ExpressJs middleware that also passes the decoded ID token in the Express request object. Uses an HTTP trigger.

Authorize with 3rd-party authentication providers

Okta, LinkedIn, Spotify, Instagram, or Basic Auth

Demonstrates how to authorize with a 3rd party sign-in mechanism, create a Firebase custom auth token, update the user's profile and authorize Firebase. Uses an HTTP trigger.

Post GitHub commits to Slack channel

Demonstrates how to automatically post GitHub commits to a Slack channel using an HTTPS triggered Function.

Create and charge customers with Stripe or Paypal

Demonstrates hows to integrate Firebase Auth and the Realtime database with Stripe via the Stripe Node.js library and shows how to create HTTP endpoints to charge customers via Paypal.

Text moderation

Demonstrates how to moderate user input text for bad words. This can be used to moderate usernames, chat or forum messages. Uses a Realtime Database trigger.

Email confirmation

Sends email confirmation after users subscribed to a mailing list. Uses a Realtime Database trigger.

Automatic message translation

Integrates the Google Translate API to perform automatic text translation across any number of languages. Language codes can be stored in Firebase for on the fly changes. Uses a Realtime Database trigger.

Automatic URL shortener

Integrates the Bit.ly API to shorten URLs automatically as they are added to the database. Uses a Realtime Database trigger.

Full-text search for Realtime Database or Firestore

Enable full-text search on Firebase Database data or Firestore documents by using a hosted search service. Uses a Realtime Database or Firestore trigger.

User data cleanup

Deletes all associated user data in the Realtime database when a user deletes his Firebase account. Uses an Auth trigger. This code has moved to its own repo at https://github.com/firebase/user-data-protection

Export your data to a Google Spreadsheet

This sample demonstrates how to sync new data written to a Firebase database to a Google Sheet. It includes a method for obtaining, storing, and using Oauth2 tokens for Google API access. Uses HTTPS triggers and Realtime Database triggers.

Export your data to Big Query

Copies Firebase Database elements into BigQuery automatically. This can be useful for instance for further logs analysis. Uses a Realtime Database trigger.

Webhook upon Firebase Database writes

Writing to the Firebase Database triggers a request to a callback URL (a Webhook). The content of the modified Data is sent to the Webhook. Uses a Realtime Database trigger.

Send a survey when users update your app

This sample shows how to send a survey to your users who have updated your app. App Update is detected using a Firebase Analytics event. Uses an Analytics trigger.

Send a coupon to user who have completed a purchase

This sample shows how to send a coupon to your users who have just purchased something. 10% off on your next purchase! Uses an Analytics trigger.

Delete inactive users accounts via cron

Periodically deletes the accounts of users who have not signed in in the last month. Uses an HTTPS trigger.

Developer Motivator

This sample demonstrates how to send a Firebase Cloud Messaging (FCM) notification to the developer device each time your app gains or loses a user. Uses an Analytics trigger.

Audio Files Conversion

This sample uses ffmpeg / fluent-ffmpeg and automatically converts audio files that are uploaded to Cloud Storage to FLAC file format with mono-channel audio @ 16000hz. Uses a Storage trigger.

Presence for Firestore

Build a simple online / offline status indicator for your users by leveraging Firestore and Realtime Database together. Uses a Realtime Database trigger.

Publish Models to Firebase ML

Automatically publishes models to Firebase ML for each TensorFlow Lite file that is uploaded to Firebase Storage.

Get information about a YouTube channel

This sample shows how to query the Youtube Data API. Uses an HTTPS trigger.

Contributing

We'd love that you contribute to the project. Before doing so please read our Contributor guide.

License

© Google, 2015-2023. Licensed under an Apache-2 license.

Build Status

Actions Status

functions-samples's People

Contributors

abeisgoat avatar ajdavid avatar appleby avatar beaspider avatar colerogers avatar dependabot[bot] avatar dpebot avatar egilmorez avatar eobrain avatar horseno avatar hramakrishnappa avatar inlined avatar jamesdaniels avatar jenperson avatar jhuleatt avatar kaibolay avatar kevded avatar kevinthecheung avatar khanhlvg avatar kroikie avatar morganchen12 avatar nicolasgarnier avatar puf avatar samtstern avatar tidoemanuele avatar trekforever avatar ultrasaurus avatar ulukaya avatar ulydev avatar yuchenshi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

functions-samples's Issues

deploying functions - FIREBASE WARNING: app/invalid-credential

This is the error

FIREBASE WARNING: {"code":"app/invalid-credential","message":"Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "read ECONNRESET"."}

How to fix?

Error: read ECONNRESET when resizing image in Storage

I'd like to resize an image stored in Firebase Storage with Firebase Functions.

Based on this example : https://github.com/firebase/functions-samples/blob/master/quickstarts/thumbnails/functions/index.js I try to write a function triggered by a Database event.

Here is the most interesting part of the code :

const gcs = require('@google-cloud/storage')();

...

const bucket = gcs.bucket('...appspot.com');
const originalFilepath = myObject.picture1Url;
const tempFilePath = '/tmp/myThumbnail';

console.log('1');

return bucket
    .file(originalFilepath)
    .download({
        destination: tempFilePath
    })
    .then(() => {

        console.log('2');

    });

Everything looks fine to me. However the code never go to the console.log('2'); and I get this error :

Error: read ECONNRESET
    at exports._errnoException (util.js:1026:11)
    at TCP.onread (net.js:569:26)

Does somebody know what could be the error?

Thank you

Deploy Error: Failed to configure trigger GCS Bucket

Hi, I'm trying out the image resizing demo. Deployment throwing error:

 Deploy Error: Failed to configure trigger GCS Bucket: product_images

My images are inside product_images folder and my code looks like this:


exports.generateThumbnail = functions.storage.object().onChange(event => {
  const object = event.data;
  const fileBucket = object.bucket;
  const filePath = object.name;
  const contentType = object.contentType;
  const resourceState = object.resourceState;

  if(!filePath.match(/product_images/)) {
    console.log('not product_images bucket');
    return;
  }

  if (!contentType.startsWith('image/')) {
    console.log('This is not an image.');
    return;
  }

  const fileName = filePath.split('/').pop();
  // Exit if the image is already a thumbnail.
  if (fileName.startsWith('thumb_')) {
    console.log('Already a Thumbnail.');
    return;
  }

  if (resourceState === 'not_exists') {
    console.log('This is a deletion event.');
    return;
  }

  const bucket = gcs.bucket(fileBucket);
  const tempFilePath = `/tmp/${fileName}`;

  return bucket.file(filePath).download({
    destination: tempFilePath
  }).then(() => {
    console.log('Image downloaded locally to', tempFilePath);
    // Generate a thumbnail using ImageMagick.
    return spawn('convert', [tempFilePath, '-thumbnail', '64x64>', tempFilePath]).then(() => {
      console.log('Thumbnail created at', tempFilePath);
      // We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail.
      const thumbFilePath = filePath.replace(/(\/)?([^\/]*)$/, `$1thumb_$2`);
      // Uploading the thumbnail.
      return bucket.upload(tempFilePath, {
        destination: thumbFilePath
      });
    });
  });
});

Not sure what it means.

Cannot find module 'mkdirp-promise'

Error: Error parsing triggers: Cannot find module 'mkdirp-promise'
full code
# firebase deploy --only functions

=== Deploying to '0000000'...

i deploying functions
i functions: ensuring necessary APIs are enabled...
i runtimeconfig: ensuring necessary APIs are enabled...
✔ runtimeconfig: all necessary APIs are enabled
✔ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...

Error: Error parsing triggers: Cannot find module 'mkdirp-promise'

Try running "npm install" in your functions directory before deploying.

Having trouble? Try firebase deploy --help

Put each function in its own file

Hi there,

How can I split my functions in its own files. I have tried to use require command, but it seems that I can't reimport resources like firebase-admin.

I am planning to write a lot of functions and put them all in index.js does not sound good.

Thanks in advance

Issues with Access-Control-Allow-Origin

I'm having issues with Access-Control-Allow-Origin in combination with Firebase Cloud Functions.

I followed the examples to protect my https endpoints to make sure that only users with a valid token can access certain eindpoints.

I configured cors en imported the cors module. The strange thing is that I encounter completely random origin errors. Sometimes the request is valid and other times the request is invalid.

Error
group

For reference and debugging, here are my cloud functions.

const cors = require('cors')({ origin: true });

const validateFirebaseIdToken = (async (req, res, next) => {
  cors(req, res, async () => {
    const authorization = req.headers.authorization;
    let decodedToken;
    if (!authorization) {
      res.status(403).send('No token Provided');
      return;
    }
    try {
      decodedToken = await admin.auth().verifyIdToken(authorization);
      req.user = decodedToken;
      next();
    } catch (error) {
      res.status(403).send('Token is invalid Provided');
      return;
    }
  });
});

const findUserByEmail = (async (req, res, next) => {
  const emailAddress = req.body.emailAddress;
  let userRecord;
  if (!emailAddress) {
    res.status(403).send('No email address provided');
    return;
  }
  try {
    userRecord = await admin.auth().getUserByEmail(emailAddress);
    req.userRecord = userRecord.toJSON();
    next();
  } catch (error) {
    if (error.code === 'auth/user-not-found') {
      next();
    }
    res.status(403).send('Something went wrong', error);
    return;
  }
});

exports.createToken = functions.https.onRequest(async (req: any, res: any) => {
  validateFirebaseIdToken(req, res, async () => {
    const organizationUID = req.body.organizationUID;
    let newToken;

    if (!organizationUID) {
      res.status(403).send('No organizationUID Provided');
      return;
    }

    const additionalClaims = {
      organizationUID
    };

    try {
      newToken = await admin.auth().createCustomToken(req.user.uid, additionalClaims);
    } catch (error) {
      res.status(403).send('Error creating a new token');
      console.log('error', error);
    }
    res.status(200).send({ token: newToken });
  });
});

exports.returnUser = functions.https.onRequest(async (req: any, res: any) => {
  validateFirebaseIdToken(req, res, async () => {
    findUserByEmail(req, res, async () => {

      if (req.userRecord) {
        const user = {
          uid: req.userRecord.uid,
          newUser: false
        };
        res.status(200).json(user);
        return;
      }
      let userRecord;
      const randomPassword = Math.random().toString(36).slice(-12);
      const newUser = {
        email: req.body.emailAddress,
        emailVerified: false,
        password: randomPassword
      };
      try {
        userRecord = await admin.auth().createUser(newUser);
        req.userRecord = userRecord.toJSON();

        const user = {
          uid: req.userRecord.uid,
          newUser: true
        };
        res.status(200).json(user);
        return;
      } catch (error) {
        res.status(403).send('Can\'t generate new user');
      }
    });
  });
});

full-text search, AlgoliaSearchNetworkError

Hi, I followed the readme on full-text search for cloud functions. Adding,modifying or deleting the blog-posts will trigger an error. Same for adding,modifying and deleteing for search/query/{queryid}.

I created an account on algolia then get the ApplicationID, and Admin API Key.
firebase functions:config:set algolia.key="<ApplicationID"> algolia.secret="<Admin API Key">

123

Error sending webhook to slack

Issue

• Following the Github to Slack example
• I am trying to send my own webhook request like this:

function postToSlack() {
  return rp({
        method: 'POST',
        uri: "https://hooks.slack.com/services/TEAM_ID/BOT_ID/API_KEY",
        body: { 
            channel: "#CHANNEL_NAME", 
            username: "webhookbot", 
            text: "MESSAGE"
        },
        json: true
    });
}

• I am getting this error

{
  "name": "RequestError",
  "message": "Error: getaddrinfo ENOTFOUND hooks.slack.com hooks.slack.com:443",
  "cause": {
    "code": "ENOTFOUND",
    "errno": "ENOTFOUND",
    "syscall": "getaddrinfo",
    "hostname": "hooks.slack.com",
    "host": "hooks.slack.com",
    "port": 443
  },
  "error": {
    "code": "ENOTFOUND",
    "errno": "ENOTFOUND",
    "syscall": "getaddrinfo",
    "hostname": "hooks.slack.com",
    "host": "hooks.slack.com",
    "port": 443
  }
}

• I tried to run the same function I am deploying in a my local node server and it works just fine

Stripe firebase

I was able to implement everything you provide in readme to integrate firebase with stripe. But, when I create a new user in firebase after i deploy the stripe from firebase cli, i cannot see the account in Stripe. I tried everything, deploy with test key, secret key, publishable key, I was unable to see my new account created in stripe sdk.
Please help.

"Child count" example, not returning correct count

In the Child count example, having copied the DB structure, the following code:

exports.countlikes = functions.database.ref('/posts/{postid}/likes').onWrite(event => { return event.data.ref.parent.child('likes_count').set(event.data.numChildren()); });

likes_count always becomes 0

trying workarounds produces even more irrational results, like the count increases sometimes, sometimes it does not increase, some other times it becomes 0 again.

There's an Stackoverflow question about this:
http://stackoverflow.com/questions/42739299/numchildren-always-returning-0

Stripe Connect

@nicolasgarnier

Sir, do you have any idea how I can do the reverse charge, meaning, I can pay my user.
Thanks to your advice, I was able to create my fiebase users charges, but I have no idea about how to pay my users. Stripe recommend the connect stripe api, but their documentation is true mess.

IOS Stripe

Hello,

Do you have any examples integrations firebase and stripe with cloud function?
Coud you give me link?

Thanks a lot

Nodemailer exemple

The exemple don't work :

=== Deploying to 'thesecretlover-b49ce'...

i deploying functions
i functions: ensuring necessary APIs are enabled...
i runtimeconfig: ensuring necessary APIs are enabled...
✔ runtimeconfig: all necessary APIs are enabled
✔ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...

Error: Error occurred while parsing your function triggers.

SyntaxError: Unexpected token ...
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:374:25)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object. (/tmp/fbfn_12080SbGGdMV34zx7/node_modules/nodemailer/lib/nodemailer.js:3:16)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)

SigningError: Could not get credentials without a JSON, pem, or p12 keyfile.

Here is the error

error getting thumbnail url { SigningError: Could not get credentials without a JSON, pem, or p12 keyfile.
at /user_code/node_modules/@google-cloud/storage/src/file.js:1463:16
at /user_code/node_modules/@google-cloud/storage/node_modules/google-auto-auth/index.js:112:7
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
message: 'Could not get credentials without a JSON, pem, or p12 keyfile.' }

Here is the code

const file = fb.bucket.file(thumbFilePath)
file.getSignedUrl({
action: 'read',
expires: '03-17-2025'
})

Infinit loop with the moderate-images example

Hi,

I've copy/paste the moderate-images example and when I'm uploading an image in Firebase Storage, it executes the cloud function like there was a loop. To stop it, I have to comment the code and deploy again.

Here is the copy/pasted code. The only difference is that I have removed to google-cloud-vision part and blurred the image every time.

// functions/index.js

'use strict';

const functions = require('firebase-functions');
const mkdirp = require('mkdirp-promise');
const gcs = require('@google-cloud/storage')();
const exec = require('child-process-promise').exec;
const LOCAL_TMP_FOLDER = '/tmp/';

/**
 * When an image is uploaded we check if it is flagged as Adult or Violence by the Cloud Vision
 * API and if it is we blur it using ImageMagick.
 */
exports.blurOffensiveImages = functions.storage.object().onChange(event => {
  const object = event.data;
  const file = gcs.bucket(object.bucket).file(object.name);

  // Exit if this is a move or deletion event.
  if (object.resourceState === 'not_exists') {
    return console.log('This is a deletion event.');
  }

  // Check the image content using the Cloud Vision API.
    return blurImage(object.name, object.bucket, object.metadata);

});

/**
 * Blurs the given image located in the given bucket using ImageMagick.
 */
function blurImage(filePath, bucketName, metadata) {
  const filePathSplit = filePath.split('/');
  filePathSplit.pop();
  const fileDir = filePathSplit.join('/');
  const tempLocalDir = `${LOCAL_TMP_FOLDER}${fileDir}`;
  const tempLocalFile = `${LOCAL_TMP_FOLDER}${filePath}`;
  const bucket = gcs.bucket(bucketName);

  // Create the temp directory where the storage file will be downloaded.
  return mkdirp(tempLocalDir).then(() => {
    console.log('Temporary directory has been created', tempLocalDir);
    // Download file from bucket.
    return bucket.file(filePath).download({
      destination: tempLocalFile
    });
  }).then(() => {
    console.log('The file has been downloaded to', tempLocalFile);
    // Blur the image using ImageMagick.
    return exec(`convert ${tempLocalFile} -channel RGBA -blur 0x8 ${tempLocalFile}`);
  }).then(() => {
    console.log('Blurred image created at', tempLocalFile);
    // Uploading the Blurred image.
    return bucket.upload(tempLocalFile, {
      destination: filePath,
      metadata: {metadata: metadata} // Keeping custom metadata.
    });
  }).then(() => {
    console.log('Blurred image uploaded to Storage at', filePath);
  });
}

And here is a screenshot of my dashboard when I only uploaded one image called "oss2.png"
capture d ecran 2017-03-25 a 16 07 11

If you have any input on it, that would be great!

Thanks!

Links are broken

Stripe charges

Hello,

I deployed stripe, registered new user which created in "stripe_customer".

How can I use this - /users/{userId}/charges/{id}.
userId is like "cus_AIUNyLkyv8mUUQ"

what is "id"?
How can I add amount to this request?

Thanks

fcm-notifications - summaryText and style

Is it possible to add summaryText and style in notification?

In node-gcm:

var message = new gcm.Message();
message.addData('title', 'My Title');
message.addData('message', 'My second message');
message.addData('style', 'inbox');
message.addData('summaryText', 'There are %n% notifications');

Analytics event trigger response time

I have a question regarding the analytics event trigger.

I am able to create a webhook that sends message to slack using functions.https trigger, and it happens almost instantly.
How long does it take between the moment that the event is fired and the execution of the function? Is it in real-time?

BigQuery import: backfill existing data

Looking at the Big Query import example, I see that it only updates BigQuery with the onWrite event.

Does it make sense to extend this example to also "backfill" BigQuery with the existing data?

I could be misunderstanding the code though. Does it already do this i.e. when you deploy this function, the onWrite will get triggered for all the existing entries in firebase, and not just the newly created ones?

Readme for Stripe

Hello

When you prepare documentations how use stripe and firebase?

Thanks

Uppercase function test undefined input

Hi guys, thanks for the examples , i am trying to get started with cloud functions but when i want to test uppercase function example there is a weird behavior , {pushId} param from test is not being correctly passing to the function , here is the logs :

the database path from test is : messages/1111/original

  Cloud Functions
    makeUpperCase
Uppercasing undefined input
      ✓ should upper case input and write it to /uppercase
    addMessage
      ✓ should return a 303 redirect

As you can see, there is a "undefined" in uppercase function , i checked event.params then the result was a empty object {}.Im just curious about this behavior I will try to debug.

Not receiving notifications when app is killed FCM with Cloud Functions for Firebase

I am currently using this approach for notifications on receiving a message from a sender.

Everything seems fine but when i kill the app I dont receive notifications.

I saw some answers regarding it that i should use just data message and receive in onMessageReceived()but its not working for killed app. What should i do?

http://stackoverflow.com/questions/42880138/not-receiving-notifications-when-app-is-killed-fcm-with-cloud-functions-for-fire

Cannot mock a DeltaSnapshot either.

I'm trying to write a unit test that calls a realtime db trigger. No matter what I pass in as my 'data' in the fakeEvent object, I'm getting the following error:

TypeError: Cannot read property 'match' of undefined
at resourceToPath (/Users/stuart/Development/apps/app-server/functions/node_modules/firebase-functions/lib/providers/database.js:109:25)
at dataConstructor (/Users/stuart/Development/apps/app-server/functions/node_modules/firebase-functions/lib/providers/database.js:85:117)
at /Users/stuart/Development/apps/app-server/functions/node_modules/firebase-functions/lib/cloud-functions.js:33:31
at process._tickCallback (internal/process/next_tick.js:103:7)

My Code:

`
const fakeEvent = {data: new functions.database.DeltaSnapshot(null, null, myData, null, myPath)};
myFunctions.userChange(fakeEvent).....;

`

Email quickstart resulting in error 534-5.7.14

Turned on Google auth, deployed app: https://functionstest-c1518.firebaseapp.com/

When logging in, I get the following error in the Function log:

Error: Invalid login: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs7
534-5.7.14 UF7mumzUwFIZrMDWiiimSdrlEvZIp8kRC3QRkzqwfOM94wkvVFys_Yjllj6KGuBubi6SwF
534-5.7.14 BDIHCpQgETRmmgkyJXfYN4Ne3uG3tnsVJk7oGR4Z5fvgeIkuOJOKkvRA8cLWFN67ya4r28
534-5.7.14 u-eBDds9bTTh1poYtxXWk1x80iaSn_2VlJHWJnB0Yql6r_-A2lDE8nt00lWP7eoUpkzVih
534-5.7.14 x1DeI0bGyNqNHRRUuucw0k95Ph-CY> Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14  Learn more at
534 5.7.14  https://support.google.com/mail/answer/78754 100sm8943270iot.39 - gsmtp
    at SMTPConnection._formatError (/user_code/node_modules/nodemailer/node_modules/smtp-connection/lib/smtp-connection.js:528:15)
    at SMTPConnection._actionAUTHComplete (/user_code/node_modules/nodemailer/node_modules/smtp-connection/lib/smtp-connection.js:1231:30)
    at SMTPConnection.<anonymous> (/user_code/node_modules/nodemailer/node_modules/smtp-connection/lib/smtp-connection.js:319:22)
    at SMTPConnection._processResponse (/user_code/node_modules/nodemailer/node_modules/smtp-connection/lib/smtp-connection.js:669:16)
    at SMTPConnection._onData (/user_code/node_modules/nodemailer/node_modules/smtp-connection/lib/smtp-connection.js:493:10)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at TLSSocket.Readable.push (_stream_readable.js:134:10)
    at TLSWrap.onread (net.js:548:20)

Stripe deploy error

Hello,

When I deployed I got error.
Error: Error parsing triggers: Cannot find module '@google-cloud/logging'

I used npm install --save @google-cloud/logging after that I made same with
I used npm install --save stripe
And deployed was success.

When I checked log I get some erorrs
1:43:57.521 ПП
outlined_flag
cleanupUser
Code in file index.js can't be loaded. Did you list all required modules in the package.json dependencies? Detailed stack trace: Error: Cannot find module '@google-cloud/logging' at Function.Module._resolveFilename (module.js:469:15) at Function.Module._load (module.js:417:25) at Module.require (module.js:497:17) at require (internal/module.js:20:19) at Object. (/user_code/index.js:20:49) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3)
Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module '@google-cloud/logging'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object. (/user_code/index.js:20:49)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)

Do you have any suggestion?

'Function killed. Error: function crashed out of request scope' when resizing

I'd like to resize an image stored in Firebase Storage with Firebase Functions.

Based on this example : https://github.com/firebase/functions-samples/blob/master/quickstarts/thumbnails/functions/index.js I tried to write a function triggered by a Database event.

Here is the most interesting part of the code :

...
    const fileName = originalPictureUrl.split('/').pop();
    const bucket = gcs.bucket('...');
    const tempFilePath = `/tmp/${fileName}`;

    return bucket
        .file(originalPictureUrl)
        .download({
            destination: tempFilePath
        })
        .then(() => {
            // Generate a thumbnail using ImageMagick.
            return spawn('convert', [tempFilePath, '-thumbnail', '200x200>', tempFilePath])
                .then(() => {

                    // We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail.
                    const thumbFilePath = filePath.replace(/(\/)?([^\/]*)$/, `$1thumb_$2`);

                    // Uploading the thumbnail.
                    return bucket.upload(tempFilePath, {
                        destination: thumbFilePath
                    });
                });
        });
...

Everything looks fine to me. However I get this error :

Function killed. Error: function crashed out of request scope

Does somebody know what could be the error?

Stripe integrations error

Hello, I added your stripe function and now try deploy it but I get follow error

i deploying functions
i functions: ensuring necessary APIs are enabled...
i runtimeconfig: ensuring necessary APIs are enabled...
✔ runtimeconfig: all necessary APIs are enabled
✔ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...

Error: Error occurred while parsing your function triggers.

TypeError: Cannot read property 'token' of undefined
at Object. (/private/var/folders/_g/nztkqsvj5tz5_383vbskcrb00000gn/T/fbfn_5850OTn7CdlyTiUL/index.js:24:59)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object. (/usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:16:9)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)

I think problem with
const stripe = require('stripe')(functions.config().stripe.token),
currency = functions.config().stripe.currency || 'USD';

How can I configure it?
Thanks

Multiple Users with same token

When multiple users registered under one device, and all of them have same token generated, how to send the FCM to specific user?

Cannot mock config.

I'm following your example exactly (I think!) and getting the following when trying to run a jasmine-based test:

functions.config() is not available. Please use the latest version of the Firebase CLI to deploy this function.

bigquery

Hi @nicolasgarnier

I am having the following error while deploying the Bigquery. Please note that the npm is already install and the dependancy is added in my package jsom. Thanks

image

FirebaseAuthError : Error not handled for email address is already in use by another account

2:55:24.027 pm
warning
oAuth_linkedin_token

Error: The email address is already in use by another account. at FirebaseAuthError.Error (native) at FirebaseAuthError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:25:28) at new FirebaseAuthError (/user_code/node_modules/firebase-admin/lib/utils/error.js:90:23) at Function.FirebaseAuthError.fromServerError (/user_code/node_modules/firebase-admin/lib/utils/error.js:114:16) at /user_code/node_modules/firebase-admin/lib/auth/auth-api-request.js:350:45 at process._tickDomainCallback (internal/process/next_tick.js:129:7)

2:55:24.024 pm
warning
oAuth_linkedin_token

Unhandled rejection

quickstarts/email-users/ --> Username and Password not accepted (3 times and rechecked)

We have been implementing the quickstarts/email-users/

With a bit of trouble and some tricky kind of error in every step always but we've managed to get to the final steps.

Nevertheless, on the last part (the test to trigger the Functions) as we got no email we checked the Registry tab in the Functions section of the Firebase Console and we found the error mentioned. So the Functions were correctly saved, the trigger is being fired correctly in both cases (new and deleted accounts) but when the Function tries to send the email it returns the error mentioned Error: Invalid login: 535-5.7.8 Username and Password not accepted.

We have already followed the process mentioned in the "Learn more link" included in the error (Verified password, Allowed less secure apps, and DisplayUnlockCaptcha button) with two different email accounts in GSuite (obviously redefining the node vars and redeploying the functions in both cases as Node asks) but it keeps saying the same, even after the third change of account, redeploy and less secure apps allowance.

Any idea on what could be the matter? Or should we try with an account outside Google's domains?

quickstart uppcase test failing

➜ functions git:(master) ✗ npm test

uppercase-quickstart-functions@ test /Users/jon/github/examples/functions-samples/quickstarts/uppercase/functions
mocha --reporter spec

Cloud Functions
makeUpperCase
1) should upper case input and write it to /uppercase
addMessage
✓ should return a 303 redirect

1 passing (152ms)
1 failing

  1. Cloud Functions makeUpperCase should upper case input and write it to /uppercase:
    TypeError: Cannot read property 'database' of null
    at DeltaSnapshot.get [as ref] (node_modules/firebase-functions/lib/providers/database.js:136:37)
    at assignValue (node_modules/lodash/lodash.js:2493:28)
    at node_modules/lodash/lodash.js:2702:9
    at arrayEach (node_modules/lodash/lodash.js:537:11)
    at baseClone (node_modules/lodash/lodash.js:2696:7)
    at node_modules/lodash/lodash.js:2702:34
    at arrayEach (node_modules/lodash/lodash.js:537:11)
    at baseClone (node_modules/lodash/lodash.js:2696:7)
    at Function.cloneDeep (node_modules/lodash/lodash.js:11102:14)
    at node_modules/firebase-functions/lib/cloud-functions.js:32:32

npm ERR! Test failed. See above for more details.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.