Coder Social home page Coder Social logo

firebase / firebase-functions Goto Github PK

View Code? Open in Web Editor NEW
1.0K 1.0K 202.0 4.49 MB

Firebase SDK for Cloud Functions

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

License: MIT License

TypeScript 80.30% Shell 0.77% JavaScript 18.90% Dockerfile 0.03%

firebase-functions's People

Contributors

abeisgoat avatar asciimike avatar berlioz avatar blidd-google avatar byeol avatar colerogers avatar dependabot[bot] avatar egilmorez avatar esmacik avatar firebase-ops avatar google-oss-bot avatar inlined avatar joehan avatar jspri avatar kaibolay avatar kevinajian avatar laurenzlong avatar leon avatar mbleigh avatar merlinnot avatar nohe427 avatar rhodgkins avatar samtstern avatar sk- avatar sknopf avatar taeold avatar thechenky avatar theirondev avatar tinaliang avatar xiaoshouzi-gh 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

firebase-functions's Issues

Stale onWrite's event.data.val() children

When subscribing to a path's onWrite event, children of event.data.val() contain stale data.
e.g. if a path is updated with a new "tag" object i.e. {tag1: true, tag2: true}, event.data.val() contains the previous version of tags. i.e. {tag1: true}

CreateCustomToken() requires a certificate with "private_key"

With the default configuration the private_key is not correctly set. Resulting in a error when calling createCustomToken():

Error: createCustomToken() requires a certificate with "private_key" set.
    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 FirebaseTokenGenerator.createCustomToken (/user_code/node_modules/firebase-admin/lib/auth/token-generator.js:62:19)
    at Auth.createCustomToken (/user_code/node_modules/firebase-admin/lib/auth/auth.js:89:37)
    at /user_code/index.js:44:26
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)

Changing the initializeApp function to this will prevent the error:


const firebaseCredential = {
  "type": "service_account",
  "project_id": "",
  "private_key_id": "",
  "private_key": "",
  "client_email": "",
  "client_id": "",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "",
  "client_x509_cert_url": ""
};

admin.initializeApp({
  credential: admin.credential.cert(firebaseCredential),
  databaseURL: xxx.firebaseio.com'
});

Currently I have the firebaseCredential inline in my code. That's not ideal. Referencing a external .json file doesn't seems the work at the moment. And storing the firebaseCredentials in a environment config doesn't work either.

FCM Notification no sound and no vibration

Version info

"firebase-admin": "^4.1.2",
"firebase-functions": "^0.5"

Were you able to successfully deploy your functions?

Yea

Expected behavior

When i receive a notification on my device it should do a sound or vibrate.

Actual behavior

I receive the notification but it don't do any sound or vibrate.

Function killed. Error: system encountered unexpected error

Version info

firebase-functions: 0.5.2
firebase-tools: 3.5.0
firebase-admin: 4.1.3

Test case

I'm triggering firebase functions at 10 minute intervals with node-schedule

One of my functions encountered an unexpected error:
Function killed. Error: system encountered unexpected error
screen shot 2017-03-23 at 10 17 11

-I'm running this function on a schedule at 10 minute intervals.
-It ran for over 17 hours before failing last night.
-The function itself uses admin messaging to send a message
-However, I console log as soon as the function is triggered, whereas the screenshot attached shows that the function never even reached my console log
-I also have this same function running identically on another project at the exact same time interval, which is still currently running without fail.

Steps to reproduce

Unsure how to reproduce.

Were you able to successfully deploy your functions?

Yes

Expected behavior

Is there anyway to catch or recover from an error like this?

Actual behavior

Function failed to run and went offline after that. (It seemed to not even hit my code as the first thing I do is console.log() a start message)

onCreate fires two times

index.js:

exports.userCreated = functions.auth.user().onCreate((event) =>
{
    ...
    admin.database().ref('userqueue').push({ ... });
 
});

If I create a new user using the Firebase web console, I consistently get two onCreate events. Quite annoying.

`Cannot GET null` when using an Express app in HTTP functions

It seems that when passing an expressJS app to an HTTP function we cannot hit the "root" URL of the function https://us-central1-app-name.cloudfunctions.net/functionName when we do we get the following error:

Cannot GET null

This despite setting a handler for all URLs for instance:

const functions = require('firebase-functions');
const express = require('express');
const app = express();
app.get('*', (req, res) => {
  res.send('Hello world');
});

exports.helloWorld = functions.https.onRequest(app);

Adding a trailing slash works. For instance: https://us-central1-app-name.cloudfunctions.net/functionName/ works normally.

Cloud function not triggered when array set to empty in parallel with other values

Version info

firebase-functions: 0.5.3

firebase-tools: n/a

firebase-admin: 4.1.3

Test case

Deploy this cloud function:

exports.testFiring = functions.database.ref('/testFire/someThing/{thingId}/tags').onWrite(event => {
  return admin.database().ref('/testFire/firedAt').set(new Date().getTime());
});

Observe the value at /testFire/firedAt while entering the following in a REPL or elsewhere:

root.child('testFire/someThing/123').set( { foo: 1, tags: ['someTag'] })

(function fires)

root.child('testFire/someThing/123').set( { foo: 2, tags: [] }

BUG: Function does not fire

For reference the function does fire when foo is not also set:

root.child('testFire/someThing/123').set( { foo: 1, tags: ['someTag'] })

(function fires)

root.child('testFire/someThing/123').set( { tags: [] })

(function fires)

Steps to reproduce

  1. Deploy cloud function above

  2. Run commands on REPL or elsewhere. Observe firedAt value.

Were you able to successfully deploy your functions?

Yes

Expected behavior

Function should always fire on array change.

Actual behavior

Function does not fire when array emptied.

Unable to deploy firebase functions

I am trying to deploy functions to cloud but getting error and log is furnished below.

PS D:\ADITYA\R&D_LIVE_CHAT\Mingle> firebase deploy --debug --only functions

Command: C:\Program Files\nodejs\node.exe C:\Users\sai\AppData\Roaming\npm\node_modules\firebase-tools\bin\firebase
deploy --debug --only functions
CLI Version: 3.5.0
Platform: win32
Node Version: v6.10.2
Time: Wed Apr 05 2017 10:13:52 GMT+0530 (India Standard Time)

command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://w
ww.googleapis.com/auth/firebase","https://www.googleapis.com/auth/cloud-platform"]
refreshing access token with scopes: ["email","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis
.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase","openid"]

HTTP REQUEST POST https://www.googleapis.com/oauth2/v3/token { refresh_token: '1/VRKOO1XfosrKVtM8EHbYmvumyxxJ-o-UFcb
QJ_Jqqc4',
client_id: '563584335869-fgrhgmd47bqnekij5i8b5pr03ho849e6.apps.googleusercontent.com',
client_secret: 'j9iVZfS8kkCEFUPaAeJV0sAi',
grant_type: 'refresh_token',
scope: 'email https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/cloudplatformprojects.rea
donly https://www.googleapis.com/auth/firebase openid' }
Wed Apr 05 2017 10:13:52 GMT+0530 (India Standard Time)
<<< HTTP RESPONSE 200 cache-control=no-cache, no-store, max-age=0, must-revalidate, pragma=no-cache, expires=Mon, 01 Jan
1990 00:00:00 GMT, date=Wed, 05 Apr 2017 04:43:53 GMT, vary=X-Origin, Origin,Accept-Encoding, content-type=application/
json; charset=UTF-8, x-content-type-options=nosniff, x-frame-options=SAMEORIGIN, x-xss-protection=1; mode=block, server=
GSE, alt-svc=quic=":443"; ma=2592000; v="37,36,35", accept-ranges=none, connection=close
HTTP REQUEST GET https://admin.firebase.com/v1/projects/mingle-be3a8
Wed Apr 05 2017 10:13:53 GMT+0530 (India Standard Time)
<<< HTTP RESPONSE 200 server=nginx, date=Wed, 05 Apr 2017 04:43:55 GMT, content-type=application/json; charset=utf-8, co
ntent-length=106, connection=close, x-content-type-options=nosniff, strict-transport-security=max-age=31536000; includeS
ubdomains, cache-control=no-cache, no-store
HTTP REQUEST GET https://admin.firebase.com/v1/database/mingle-be3a8/tokens
Wed Apr 05 2017 10:13:54 GMT+0530 (India Standard Time)
<<< HTTP RESPONSE 200 server=nginx, date=Wed, 05 Apr 2017 04:43:57 GMT, content-type=application/json; charset=utf-8, co
ntent-length=425, connection=close, x-content-type-options=nosniff, strict-transport-security=max-age=31536000; includeS
ubdomains, cache-control=no-cache, no-store

=== Deploying to 'mingle-be3a8'...

i deploying functions

[functions] package.json contents: {
"name": "functions",
"description": "Cloud Functions for Firebase",
"dependencies": {
"firebase-admin": "^4.1.2",
"firebase-functions": "^0.5"
},
"private": true
}
i functions: ensuring necessary APIs are enabled...
i runtimeconfig: ensuring necessary APIs are enabled...

HTTP REQUEST GET https://servicemanagement.googleapis.com/v1/services/cloudfunctions.googleapis.com/projectSettings/
mingle-be3a8?view=CONSUMER_VIEW
Wed Apr 05 2017 10:14:01 GMT+0530 (India Standard Time)
HTTP REQUEST GET https://servicemanagement.googleapis.com/v1/services/runtimeconfig.googleapis.com/projectSettings/m
ingle-be3a8?view=CONSUMER_VIEW
Wed Apr 05 2017 10:14:01 GMT+0530 (India Standard Time)
<<< HTTP RESPONSE 200 content-type=application/json; charset=UTF-8, vary=X-Origin, Referer, Origin,Accept-Encoding, date
=Wed, 05 Apr 2017 04:44:03 GMT, server=ESF, cache-control=private, x-xss-protection=1; mode=block, x-frame-options=SAMEO
RIGIN, x-content-type-options=nosniff, alt-svc=quic=":443"; ma=2592000; v="37,36,35", accept-ranges=none, connection=clo
se

  • runtimeconfig: all necessary APIs are enabled
    <<< HTTP RESPONSE 200 content-type=application/json; charset=UTF-8, vary=X-Origin, Referer, Origin,Accept-Encoding, date
    =Wed, 05 Apr 2017 04:44:03 GMT, server=ESF, cache-control=private, x-xss-protection=1; mode=block, x-frame-options=SAMEO
    RIGIN, x-content-type-options=nosniff, alt-svc=quic=":443"; ma=2592000; v="37,36,35", accept-ranges=none, connection=clo
    se
  • functions: all necessary APIs are enabled

HTTP REQUEST GET https://appengine.googleapis.com/v1/apps/mingle-be3a8
Wed Apr 05 2017 10:14:03 GMT+0530 (India Standard Time)
HTTP REQUEST GET https://apikeys.googleapis.com/v1/projects/mingle-be3a8/apiKeys
Wed Apr 05 2017 10:14:03 GMT+0530 (India Standard Time)
<<< HTTP RESPONSE 200 content-type=application/json; charset=UTF-8, vary=X-Origin, Referer, Origin,Accept-Encoding, date
=Wed, 05 Apr 2017 04:44:05 GMT, server=ESF, cache-control=private, x-xss-protection=1; mode=block, x-frame-options=SAMEO
RIGIN, x-content-type-options=nosniff, alt-svc=quic=":443"; ma=2592000; v="37,36,35", accept-ranges=none, connection=clo
se
<<< HTTP RESPONSE 200 content-type=application/json; charset=UTF-8, vary=X-Origin, Referer, Origin,Accept-Encoding, date
=Wed, 05 Apr 2017 04:44:05 GMT, server=ESF, cache-control=private, x-xss-protection=1; mode=block, x-frame-options=SAMEO
RIGIN, x-content-type-options=nosniff, alt-svc=quic=":443"; ma=2592000; v="37,36,35", accept-ranges=none, connection=clo
se
i functions: preparing functions directory for uploading...
HTTP REQUEST GET https://runtimeconfig.googleapis.com/v1beta1/projects/mingle-be3a8/configs
Wed Apr 05 2017 10:14:54 GMT+0530 (India Standard Time)
<<< HTTP RESPONSE 200 content-type=application/json; charset=UTF-8, vary=X-Origin, Referer, Origin,Accept-Encoding, date
=Wed, 05 Apr 2017 04:44:55 GMT, server=ESF, cache-control=private, x-xss-protection=1; mode=block, x-frame-options=SAMEO
RIGIN, x-content-type-options=nosniff, alt-svc=quic=":443"; ma=2592000; v="37,36,35", accept-ranges=none, connection=clo
se
[functions] runtime config materialized as: {
"firebase": {
"databaseURL": "https://mingle-be3a8.firebaseio.com",
"storageBucket": "mingle-be3a8.appspot.com",
"apiKey": "AIzaSyC2KKWrTIwKYFzDJzYbNLSDELjCS-PhxKs",
"authDomain": "mingle-be3a8.firebaseapp.com"
}
}
[functions] parsed triggers: [
{
"httpsTrigger": {},
"name": "addMessage",
"entryPoint": "addMessage"
}
]
Error: ENOTEMPTY: directory not empty, rmdir 'C:\Users\sai\AppData\Local\Temp\fbfn_1892YPzPCgcquJf3\node_modules'
at Error (native)
at Object.fs.rmdirSync (fs.js:887:18)
at rmkidsSync (C:\Users\sai\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\rimraf\rimraf.js:355:25)
at rmdirSync (C:\Users\sai\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\rimraf\rimraf.js:333:7)
at rimrafSync (C:\Users\sai\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\rimraf\rimraf.js:303:9)
at C:\Users\sai\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\rimraf\rimraf.js:341:5
at Array.forEach (native)
at rmkidsSync (C:\Users\sai\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\rimraf\rimraf.js:340:26)
at rmdirSync (C:\Users\sai\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\rimraf\rimraf.js:333:7)
at Function.rimrafSync [as sync] (C:\Users\sai\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\rimraf\r
imraf.js:303:9)

Error: An unexpected error has occurred.
i functions: packaged functions (997 B) for uploading

HTTP REQUEST GET https://www.googleapis.com/storage/v1/b/staging.mingle-be3a8.appspot.com
Wed Apr 05 2017 10:15:00 GMT+0530 (India Standard Time)

Import default issue with babel@6

Firebase-functions version is 0.5.4

I am using babel@6 to transpile my es6 code and found an issue that the transpiled code is not working. Here's how to reproduce:

import functions from 'firebase-functions'

export const helloWorld = functions.https.onRequest((request, response) => {
  response.send('Hello World!')
})

which is transpiled into (using babel@6 es2015 preset):

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.helloWorld = undefined;

var _firebaseFunctions = require('firebase-functions');

var _firebaseFunctions2 = _interopRequireDefault(_firebaseFunctions);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var helloWorld = exports.helloWorld = _firebaseFunctions2.default.https.onRequest(function (request, response) {
  response.send('Hello World!');
});

which produces the following error when deploying:

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

Error: Error occurred while parsing your function triggers.

TypeError: Cannot read property 'https' of undefined
    at Object.<anonymous> (/private/var/folders/6q/__dzccnj1p7_k7vz2qp2ntdr0000gn/T/fbfn_21971bAqbpyOqCko0/index.js:14:66)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:16:9)
    at Module._compile (module.js:571:32)

I think the issue is that firebase-functions did not export a default and hence, when importing a default (import functions from 'firebase-functions'), the transpiled code does not work. This could be related to babel's T2212 Kill CommonJS default export behaviour.

A quick workaround is to import the individual package instead of importing the default:

import { https } from 'firebase-functions'

export const helloWorld = https.onRequest((request, response) => {
  response.send('Hello World!')
})

which transpiles into:

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.helloWorld = undefined;

var _firebaseFunctions = require('firebase-functions');

var helloWorld = exports.helloWorld = _firebaseFunctions.https.onRequest(function (request, response) {
  response.send('Hello World!');
});

which has no issue to run and to deploy.

The fix should be a relatively easy one which is to explicitly export a default in firebase-functions.

Deploy Error: Failure in the execution environment

Hi there,
I encountered these kind of bug randomly, and fortunately after several tries, it succeeded as it should.
I've attached some screenshots below as a contribution to eliminate the bug.
Anyway, Firebase Functions is a magical feature and it makes life easier and happier 👍
Hope to see a stable system soon.
Thank you so much, Firebase Team :)

firebase-functions-bug-console

firebase-functions-bug

Cannot install firebase-functions

I am currently unable to firebase deploy because firebase-functions won't get installed, and it won't even omit them when I tell it to during firebase init.

Here is the problem with firebase-functions in particular:

During npm install in my functions folder, I am told that the @types/express dependency does not exist:

npm http 404 https://registry.npmjs.org/types/express
npm ERR! 404 Not Found
npm ERR! 404
npm ERR! 404 'types/express' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404 It was specified as a dependency of 'firebase-functions'

When just running npm install --save @types/express, I get a different error:

d:\code\self-asssessment-app\functions>npm install --save @types/express
npm WARN git config --get remote.origin.url returned wrong result (git://github.com/types/express)
npm WARN git config --get remote.origin.url returned wrong result ([email protected]:types/express)
npm ERR! git clone [email protected]:types/express Cloning into bare repository 'C:\Users\Domi\AppData\Roaming\npm-cache_git-remotes\git-github-com-types-express-baf9b5a2'...
npm ERR! git clone [email protected]:types/express Permission denied (publickey).
npm ERR! git clone [email protected]:types/express fatal: Could not read from remote repository.
npm ERR! git clone [email protected]:types/express
npm ERR! git clone [email protected]:types/express Please make sure you have the correct access rights
npm ERR! git clone [email protected]:types/express and the repository exists.
npm ERR! addLocal Could not install types/express
npm ERR! Error: ENOENT: no such file or directory, stat 'd:\code\self-asssessment-app\functions\types\express'
npm ERR! If you need help, you may report this entire log,
npm ERR! including the npm and node versions, at:
npm ERR! http://github.com/npm/npm/issues

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\Program Files\nodejs\node.exe" "C:\ProgramData\chocolatey\lib\npm\tools\node_modules\npm\bin\npm-cli.js" "install" "--save" "@types/express"
npm ERR! cwd d:\code\self-asssessment-app\functions
npm ERR! node -v v7.2.1
npm ERR! npm -v 1.4.9
npm ERR! path d:\code\self-asssessment-app\functions\types\express
npm ERR! syscall stat
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! d:\code\self-asssessment-app\functions\npm-debug.log
npm ERR! not ok code 0

I am on Windows, and my firebase-tools are the latest version:

$npm list -g firebase-tools
C:\Program Files\nodejs
└── [email protected]

functions/package.json contains the following dependencies (and functions/node_modules is empty):

  "dependencies": {
    "firebase-admin": "^4.1.2",
    "firebase-functions": "^0.5"
  }

Any help would be greatly appreciated. Also, it worked just fine yesterday... on a different machine though...

Can't serve firebase-functions locally, even with Node v6.11

[email protected]
[email protected]
[email protected]

Test case

Trying to serve functions locally

Steps to reproduce

Install nvm
nvm use v6.9.1
install dependencies
now run:
firebase serve --only functions

Expected behavior

That the functions are hosted locally

Actual behavior

The log file is deleted, but I get this output:

=== Serving from '/Users/alexbjorlig/Documents/Github/amentoCph'...

i functions: Preparing to emulate HTTPS functions. Support for other event types coming soon.
Node.js v6.11.x or greater is required to run the Emulator!
⚠ functions: Failed to load functions source code. Ensure that you have the latest SDK by running npm i --save firebase-functions inside the functions directory. Please note that emulation of custom config values are not supported yet. Run firebase serve --only hosting to only serve hosting files.

Error: Emulator crashed! Check the log file...
i functions: No HTTPS functions emulated. Support for other function types are coming soon.

npm ERR! 404 Not Found

While installing npm package getting following messages:
...functions>npm i firebase-functions
npm WARN package.json time-server-functions@ No repository field.
npm WARN package.json time-server-functions@ No README data
npm ERR! 404 Not Found
npm ERR! 404
npm ERR! 404 'types/jsonwebtoken' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404 It was specified as a dependency of 'firebase-functions'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.

Firebase function not responding to Pub/Sub message

Version info

firebase-functions: 3.10.10

firebase-tools: 3.10.10

firebase-admin: 3.10.10

Test case

I feel like I might be missing something simple, but I can't get a Firebase cloud function to respond to a Pub/Sub published message. It works fine when I deploy using gloud and opt for the Admin SDK for Node.js, but auth is tricky; it works for the first write and then it fails to authenticate.

With the release of Firebase cloud functions, I decided to try again. My function code is as follows:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

function pushOrderToFirebase(completedOrder) {

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

  //setters and getters for the message that will be pushed to firebase

  admin.database().ref('/orders').push({
    name: curDriverName,
    recipient: recipient,
    address: address,
    details: details,
    isDelivered: isDelivered,
    failureReason: failureReason,
    time: formattedTime
  }).then(snapshot => {
    console.log(snapshot);
  });
}
exports.firebasePusherAlpha = functions.pubsub.topic('test-topic').onPublish(event => {
  const pubSubMessage = event.data;

  let parsedMessage = null;
  try {
    parsedMessage = pubSubMessage.json;
    console.log(parsedMessage);
  } catch (e) {
    console.error('PubSub message was not JSON', e);
  }
  pushOrderToFirebase(parsedMessage);
  callback();
});

Were you able to successfully deploy your functions?

Function deploys successfully.

Expected behavior

Cloud function responding to pubsub message by writing to firebase.

Actual behavior

Function does not get called.

Permission denied on set value

I am simply doing this:
admin.database().ref(/chat/last_message/${currentUserId}).set(currentTimestamp);

however I get:

FIREBASE WARNING: set at /chat/last_message/46wyOyreyYSocywqEt1g3943OAH2 failed: permission_denied

even though my database rule is only:

"chat": {
      "last_message": {
        "$uid": {
          ".write": true
        }
      },
}

Strange thing is I do the exact thing on my other firebase account, and it worked perfectly fine.

Error: function crashed out of request scope Function killed.

I'm using database onWrite() function. Getting the below error randomly,

Error: function crashed out of request scope Function killed.

Couldn't find more detail regarding this error. Code inside the function block is working fine, when I run at local machine. Getting this error only after deploying my function in server.

Appreciate your help on this.

Typescript

Can we use typescript to write firebase functions at the moment? I saw that we can per https://youtu.be/GNR9El3XWYo?t=13m46s but I am not sure how to configure it.

If we can use typescript can you please provide an example.

Thanks

Can't install firebase-functions due to dependency problem

Version info

firebase-functions: 0.5.9

firebase-tools:

firebase-admin: 5.0.1

Test case

My Firebase app is configured with functions, although I haven't used them yet.

Steps to reproduce

To use functions (I need them to read environment variables for my app configuration) I tried to npm i firebase-functions -S. This gave a warning:

npm WARN [email protected] requires a peer of firebase-admin@~4.2.1 but none was installed.

So I tried to npm i firebase-admin. But that still gives me the above warning. Seems to me, that firebase-functions only works with an older version of firebase-admin. So I tried to install the older version by npm i firebase-admin@~4.2.1 -S.

But that gives me the following error when trying to start my react application:

Module not found: Can't resolve 'dns' in '/Users/morgler/code/dreimannzelt/sonnendepot/pricing/node_modules/firebase-admin/node_modules/isemail/lib'

Were you able to successfully deploy your functions?

No

Expected behavior

I don't really need functions. I simply want to read ENV variables for configuring staging and production environments differently. npm i firebase-functions should simply work.

Actual behavior

I get dependency warnings. Even when trying to install the exact version of the dependency, I get errors.

Change region http trigger

Is it possible to deploy an http trigger cloud function to a region other than us-central1?
We experience latency due to interregional requests.

How do i point to latest firebase-functions in github.com under package.json

https://www.npmjs.com/package/firebase-functions is currently outdated.
I am looking to use the latest github as resourceState has just been added.

{
  "name": "generate-thumbnails-functions",
  "description": "Generate thumbnails",
  "dependencies": {
    "@google-cloud/storage": "^0.4.0",
    "child-process-promise": "^2.2.0",
    "firebase-admin": "^4.1.3",
    "firebase-functions": "git+https://github.com/firebase/firebase-functions.git"
  }
}

On compiling with typescript, it's having an error
Cannot find module 'firebase-functions'

$ npm install firebase/firebase-functions --save
└── [email protected]  (git://github.com/firebase/firebase-functions.git#e9efdd372e5240df68728149f1fa2625e0e20d4d)

$ ls node_modules/firebase-functions/
CONTRIBUTING.md LICENSE     README.md   changelog.txt   package.json

I am not seeing the lib directory in there

Error: Error parsing triggers: Cannot find module

I am trying to deploy my firebase function to cloud but getting an error:

Error: Error parsing triggers: Cannot find module 'EmailData'

1.I compile my ts file to js.

2.the build of ts ok... my code looks like:

the ts that importing the file...

var EmailDataClass = require("EmailData");
and the file it self:

class EmailData {....
}export = EmailData;

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

Error: Error parsing triggers: Cannot find module 'EmailData'

db.orderByChild().equalTo().once('value') different result from db.child().once('value')

I'm confused as to why a seemingly identical call but slightly different method harbors 1 result and 1 failed result.

expect result: console to log the id in this case 42

FAILS

  const postId = 42;

  admin.database().ref('/news').orderByChild('id').equalTo(postId).once('value').then(snapshot => {
    const post = snapshot.val();
    post.id = snapshot.key;

    console.log(post.id)

  })

SUCCESS

const postId = 42;

  admin.database().ref('/news').child(postId).once('value').then(snapshot => {

        const post = snapshot.val();
        post.id = snapshot.key;

        console.log(post.id)
    })

The reason I'm trying to query the database on a string rather then a post ID

ERROR: getaddrinfo ENOTFOUND

Version info

firebase-functions: 0.5.7

firebase-tools: 3.9.1

firebase-admin: 4.2.1

Test case

Hello. Thank you for read me.

I have the following case:
I'm trying to do an http GET request from firebase function, this is my code:
(I'm using a test API from "jsonplaceholder" just to get Random Data and then test my real functionality.)

const functions = require('firebase-functions');
const http = require('http');

exports.myFunction= functions.https.onRequest((request, response) => {
     var options = {
          host: 'jsonplaceholder.typicode.com',
          path: '/posts/1',
     };

    var req = http.get(options, function(res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));

    // Buffer the body entirely for processing as a whole.
    var bodyChunks = [];
    res.on('data', function(chunk) {
        bodyChunks.push(chunk);
    }).on('end', function() {
        var body = Buffer.concat(bodyChunks);
        console.log('BODY: ' + body);
        })
    });

    req.on('error', function(e) {
    console.log('ERROR: ' + e.message);
    });

    response.send("Hello from Firebase!"); //just to send something in response.
 }

Steps to reproduce

When I test that function in my LOCAL environment on a test case using node index.js, everything works just fine!

Were you able to successfully deploy your functions?

When I do firebase deploy everything deploys just fine, the function is uploaded to my function dashboard.

Expected behavior

The expected behavior is that the log printing the body returns something like:

STATUS: 200
BODY: {
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae 
    ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Actual behavior

The actual behavior is this:

ERROR: getaddrinfo ENOTFOUND https://jsonplaceholder.typicode.com https://jsonplaceholder.typicode.com:443

Thats what's happening when I trigger the function on firebase, but in my local environment everything work ust fine.. is that a bug?

Thank you very much!

Using database's set with an object with two properties will not trigger function which listenes to one of the properties

Version info

firebase-admin: 4.1.2,
firebase-functions: 0.5

Test case & Steps to reproduce

https://github.com/Portals/firebase_functions_database_bug

Bug in summary:

This will trigger a function listening to /path/1

        firebase.database().ref("/path").set({
          1: "Sweden",
          2: "Hello World"
        });

This will trigger a function listening to /path/1
firebase.database().ref("/path").remove();

This will not trigger a function listening to /path/1

        firebase.database().ref("/path").set({
          1: null,
          2: "Hello World"
        });

This will trigger a function listening to /path/1

        firebase.database().ref("/path").set({
          1: null,
          2: null
        });

This is the function which listens to /path/1

var functions = require('firebase-functions');

exports.updateSweden = functions.database.ref("/path/1").onWrite(event => {
  const oldData = event.data.previous.val();
  const newData = event.data.val();

  console.log("oldData: " + oldData);
  console.log("newData: " + newData);
});

Were you able to successfully deploy your functions?

Yes

Expected behavior

The function which listens to /path/1 doesn't run.

Actual behavior

The function which listens to /path/1 should run

Can i use http request to another api?

I am making a viability to use firebase-functions and would like to know if it is possible to communicate with another api using http request.

Anyone already tested?

No permission to view the "datastore provider" access request form

This is not really an issue with the functions SDK but since the form to request access to the datastore provider is listed in the README I am reporting it here.

This is what I am seeing in the form page:

You need permission
This form can only be viewed by users in the owner's organization.

Try contacting the owner of the form if you think this is a mistake. Learn More.

Thanks!

nextjs with firebase cloud functions

Hi,
i want use nextjs with firebase and run the server on cloud functions.

i have this index.js in functions dir:

import * as functions from 'firebase-functions';
import cors from 'cors';
import express from 'express';
import next from 'next';

const nextApp = next({ dev: false });
const handle = nextApp.getRequestHandler();

nextApp
  .prepare()
  .then(() => {
    const server = express();
    server.use(cors({ origin: true }));

    server.get('/a', (req, res) => {
      return nextApp.render(req, res, '/b', req.query);
    });

    server.get('/b', (req, res) => {
      return nextApp.render(req, res, '/a', req.query);
    });

    server.get('*', (req, res) => {
      return handle(req, res);
    });
  })
  .catch(ex => {
    console.error(ex.stack);
    process.exit(1);
  });

export let app = functions.https.onRequest(nextApp);

The problem is that i can't upload on the cloud the nextjs build folder.
How i can include this folder?

vercel/next.js#2017

Changes to functions are not deployed

Version info

firebase-functions:
0.5.9
firebase-tools:
3.9.1
firebase-admin:
4.2.1

Test case

Deploying functions the first time works.
But the second time, I get the "Deploy complete" message quickly, and the changes to the existing functions are not deployed.

Steps to reproduce

firebase deploy --only functions

Were you able to successfully deploy your functions?

Yes, but only the first time.

Expected behavior

After making changes to the functions, they should actually redeploy.

Actual behavior

I recieve the message "Deploy complete!", but nothing happens.
Here is the output:

=== Deploying to 'amentocph-test'...

i deploying
i starting release process (may take several minutes)...

✔ Deploy complete!

Permission denied in firebase cloud functions

I have created stack question here https://stackoverflow.com/questions/44440897/permission-denied-in-firebase-cloud-functions.

I get access denied when I am trying to access realtime db from cloud functions.
Here is screenshot of keys: http://imgur.com/a/cCpkB

I created this project in february and I am working with it on react-native. Before implementing cloud-functions I have generated admin sdk key for node.js which works fine.

Version info

**firebase-functions: 0.5.7

**firebase-tools: 3.9.1

**firebase-admin: 5.0.0

Steps to reproduce

I don't know how to reproduce this issue, when I created new firebase project I did not have this problem.

Were you able to successfully deploy your functions?

Yes

Getting strange errors on app deleted and ECONNRESET

Version info

firebase-functions: 0.5.2
firebase-tools: 3.5.0
firebase-admin: 4.1.3

Test case

Unsure of the test case as it seems to be caused by an ECONNRESET on firebase functions. However it may be caused by me returning promises incorrectly.

Steps to reproduce

I'm writing a progress percentage to the events ref, as my job progresses, with a function:

function progress(percentage) {
    return event.data.adminRef.child('_progress').set(percentage)
}

I'm hitting a strange ECONNRESET error and and an app error seen below.
It's only happening on one of my functions repeatedly, and I'm thinking it might be how I'm returning the promise here. When I call the progress(10) percentage throughout my function, is it enough to do something like this:

...
function progress(percentage) {
    return event.data.adminRef.child('_progress').set(percentage)
}
progress(10);
...

Will that keep my firebase-function running or do I also have to return the function?
return progress(10);

Could that be whats causing the below strange intermittent errors?

Were you able to successfully deploy your functions?

Yes

Actual behavior

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"."}

And

Error: Firebase app named "admin" has already been deleted.
at FirebaseAppError.Error (native)
at FirebaseAppError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:25:28)
at new FirebaseAppError (/user_code/node_modules/firebase-admin/lib/utils/error.js:70:23)
at FirebaseApp.checkDestroyed_ (/user_code/node_modules/firebase-admin/lib/firebase-app.js:249:19)
at FirebaseApp.getService_ (/user_code/node_modules/firebase-admin/lib/firebase-app.js:232:14)
at DeltaSnapshot.get [as adminRef] (/user_code/node_modules/firebase-functions/lib/providers/database.js:146:48)
at progress (/user_code/new_order.js:16:30)
at Promise.all.then.result (/user_code/new_order.js:56:17)
at process._tickDomainCallback (internal/process/next_tick.js:129:7)

functions.auth.user().onCreate() is triggered when user is anonymous

Version info

firebase-functions: 0.5.9

firebase-tools: 3.9.1

firebase-admin: 4.2.1

Steps to reproduce

Sign in first time anonymously from iOS or Android

Were you able to successfully deploy your functions?

Yes

Expected behavior

functions.auth.user().onCreate() shouldn't be triggered according to this documentation

The following account creation methods do not currently trigger Cloud Functions events: A user signs in for the first time using a custom token. A user signs in to a new anonymous auth session for the first time.

Actual behavior

functions.auth.user().onCreate() is triggered

Require another files into index.js

I see that all functions reside in a single index.js file.
How can i create another files and require it in the index.js?
I'm trying to organize my functions.

Functions initialisation with const gives error

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.CreateUser = functions.auth.user().onCreate(event => {
  console.log('User Created');
});

When deploying this function i get error


Error: Error occurred while parsing your function triggers.

SyntaxError: missing ) after argument list
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:413:25)
    at Object.Module._extensions..js (module.js:448:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:16:9)
    at Module._compile (module.js:430:26)
    at Object.Module._extensions..js (module.js:448:10)

changing const functions to var functions make this works.

firebase cli - 3.5.0
node - 3.3.1

`event.params` is undefined in unit tests

Version info

firebase-functions: 0.6.2
firebase-tools: 3.9.2
firebase-admin: 5.2.1

Test case

//
// In unit test
//
// ...
event = {
  params: {
    userId: 'user-id',
  },
  data: new functions.database.DeltaSnapshot(null, admin, null, user)
};
console.log(event); // 1st log
await myFunctions.onUserWrite(event);
// ...
//
// In onUserWrite
//
export.onUserWrite = functions.database.ref('/users/userId').onWrite(async event => {
  // ...
  console.log(event); // 2nd log
  // ...
);

Were you able to successfully deploy your functions?

No, since unit tests fail

Expected behavior

1st log should equal 2nd log, showing both event.params.userId as user-id

Actual behavior

1st log shows event.params.userId as user-id
2nd log shows event.params.userId as undefined; However, the event.data element is equal to the 1st log!


Reverting back to firebase-functions: 0.6.1 fixes the issue.

onWrite function takes 15 seconds to begin

Version info

firebase-functions: "^0.5"

firebase-admin: "^4.1.2"

Test case

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.functionName = functions.database.ref('/Something/{somethingId}').onWrite(event => {
	const snapshot = event.data;
	const something = snapshot.val();
	
	if (something) {
		console.log('Cloud function executing...');
	}
});

Steps to reproduce

Add object under "Something" reference and look at the console when the message "Cloud function executing...".

Were you able to successfully deploy your functions?

No error message when I deployed the function.

Expected behavior

The message should appear directly when the object is added to the database.

Actual behavior

The message is appearing 15s after the object appear in database.

Deploy Error: Failed to retrieve function source code

Version info

firebase-functions: 0.5.2
firebase-tools: 3.5.0
firebase-admin: 4.1.3

Steps to reproduce

Only 15 out of 17 of my functions are deploying successfully

Were you able to successfully deploy your functions?

Not exactly,
I'm getting the following error since deploying my 17th function:

...
i  functions: updating function primeFunctions...
⚠  functions[orderStateChange]: Deploy Error: Failed to retrieve function source code
⚠  functions[slackPost]: Deploy Error: Failed to retrieve function source code
...

screen shot 2017-03-22 at 13 36 47

Expected behavior

Successful deployment of all 17 functions

Actual behavior

Two functions receive the above error. Deployment takes longer than usual to complete. Strangely it's 2 different functions each time that fail to retrieve the source code.

Transaction not resolving correctly, timing out functions

Function is timing out when using transactions:

exports.ObserveProposals = functions.database.ref("/proposals/{jobid}/{propid}").onWrite((event) => {
  const jobid = event.params.jobid;
  const userid = event.params.propid;
  let userRef = admin.database().ref(`/users/${userid}`);
  let jobRef = admin.database().ref(`/jobs/${jobid}/proposals`);
  const jobRefPromise = jobRef.once('value');
  return Promise.all([jobRefPromise]).then(results => {
    const promises = [];
    const jobRefSnapshot = results[0];
    if (event.data.exists() && !event.data.previous.exists()) {
      if (jobRefSnapshot.val() !== null) {
        const IncrementProposalJob = jobRef.transaction(current => {
          return (current || 0) + 1;
        });
        promises.push(IncrementProposalJob);
      }
      let type = event.data.child("isinvitation").val() ? 'received' : 'sent';
      const allocateUserProposal = userRef.child(`/proposals/${type}/${jobid}`).set({
        timestamp: admin.database.ServerValue.TIMESTAMP
      });
      promises.push(allocateUserProposal);
      if (type === 'received'){
        const sendUserNotification = userRef.child("/notifications").push({
          timestamp: admin.database.ServerValue.TIMESTAMP,
          key: jobid,
          type: 1
        });
        promises.push(sendUserNotification);
      }
    } else if (!event.data.exists() && event.data.previous.exists()) {
      let type = event.data.previous.child("isinvitation").val() ? 'received' : 'sent';
      if (jobRefSnapshot.val() !== null) {
        const subProposalJobpromise = jobRef.transaction(current => {
          return (current || 0) - 1;
        });
        promises.push(subProposalJobpromise);
      }
      const removeAllocateUserProposal = userRef.child(`/proposals/${type}/${jobid}`).remove();
      promises.push(removeAllocateUserProposal);
    }
    return Promise.all(promises);
  });
});

functions:config:clone results in escaped quotes within nested values

Version info

firebase-functions: 0.5.3

firebase-tools: 3.6.1

firebase-admin: 4.1.3

Test case

When cloning config environment, nested values have escaped quotes.

Steps to reproduce

firebase use env1
firebase functions:config:set someservice.key="key"
firebase deploy
firebase use env2
firebase functions:config:clone --from env1
firebase functions:config:get

Outputs:

{
  "someservice": {
    "key": "\"key\""
   }
]

Were you able to successfully deploy your functions?

Yes

Expected behavior

Same config settings.

Actual behavior

Invalid config values

functions.database.DeltaSnapshot#key outputs incorrect value

Version info

firebase-functions: ^0.5

firebase-admin: ^4.1.4

Test case

This is similar to what I have:

const functions = require('firebase-functions');

exports.myFunction = functions.database.ref('/Accounts/{uId}/{accountId}/')
    .onWrite(event => {
	 event.data.current.forEach(function(item) {
	     console.log(item.key);
	 });
    });

Were you able to successfully deploy your functions?

Yup. I'd classify this as more of a semantic error.

Expected behavior

If my path was /Accounts/1234/5678, the key should give me 5678.

Actual behavior

The key property gives me 12345678 (combining the second and third level children).

Temporary fix

I put this on top of my index.js file, and it seems to fix the problem, though it might not cover all cases.

const functions = require('firebase-functions');

functions.database.DeltaSnapshot.prototype._fullPath = function () {
    var out = (this._path || '') + '/' + (this._childPath || '');
    if (out === '') {
        out = '/';
    }
    return out;
}

Deploy Error: Insufficient permissions to (re)configure a trigger

Version info

firebase-functions:
0.5.5
firebase-tools:
3.6.1
firebase-admin:
4.2.1

Test case

Uploading the following index.js file to functions:

const functions = require('firebase-functions');

exports.discoverText = functions.storage.object().onChange(event => {
  const object = event.data;
  console.log('The object is', object);
});

Steps to reproduce

This is a brand new project, just created -- I took a function that I've been testing and did a firebase deploy --only functions

UPDATE
Created a brand new project, tried to deploy, got the same error.

Were you able to successfully deploy your functions?

!  functions[discoverText]: Deploy Error: Insufficient permissions to (re)configure a trigger (permission denied for bucket functions-test-7f0c5.appspot.com). Please, give owner permissions to
 the editor role of the bucket and try again.

Expected behavior

I expect this function to deploy normally as it did not 10 minutes before. With zero code changes, it suddenly stopped deploying properly

Actual behavior

Deployment failed.

Running the provided https function example locally does not work

Version info

node: 6.11.0

npm: 3.10.10

firebase-functions: 0.5.9

firebase-tools: 3.10.10

firebase-admin: 4.2.1

Test case

I tried running the (commented out) https function you get by running firebase init functions locally.
Always get the following message (even after installing firebase-functions inside the functions directory:

functions: Failed to load functions source code. Ensure that you have the latest SDK by running npm i --save firebase-functions inside the functions directory. Please note that emulation of custom config values are not supported yet. Run firebase serve --only hosting to only serve hosting files.

Error: Emulator crashed! Check the log file...

The Log file is deleted instantly.

Steps to reproduce

mkdir functiontest
cd functiontest
firebase init functions
cd functions
cd ../

commenting out line 6-8 from the generated index.js

firebase serve --only functions
cd functions
npm i --save firebase-functions
cd ../
firebase serve --only functions

Were you able to successfully deploy your functions?

Deploying works as expected.

Expected behavior

Serving the helloWorld function locally.

Actual behavior

see above
The local Log file is deleted instantly.

Testing database functions locally

It looks like firebase cli tool bundles all dependencies and upload it to firebase just like aws lambda function does. But it takes too much time to be done even on minor changes in code and also need a good connectivity of internet . If you are offline for some reason, you are just in dark what code you are writing until you have a way to execute and test that functions offline on your local machine.

Is there any way to test firebase functions locally?
if there is no, then why?

Curly brackets (`{}`) in the `path` name.

Hey guys,

Cloud Functions allows wildcards in the path name.
So, I can do something like this "messages/{messageId}" which will match to "messages/messageId1", "messages/messageId2" and etc...

My question is...
Is it possible to use this technic with Firebase Admin SDK?
or somehow use firebase-functions in my own server?

Returning promise using cors or other middleware

I have a promise chain in my function and want to enable cors, but to do so I need to wrap my function like that:

module.exports = (req, res) => {
  cors(req, res, () => {
    return thisReturnsPromise()
      .then((errands) => {
        res.status(200).send('OK')
      })
      .catch((error) => {
        res.status(500).send(`Error.`);
      });
  });
};

https://www.npmjs.com/package/cors

The problem is that cors doesn't care if the callback returns promise, so my function cannot wait for my promises and also testing is impossible.

How can I have cors and promises at the same time?

user.create function not triggered for Phone Auth

Version info

firebase-functions: 0.5.7

firebase-tools: 3.9.0

firebase-admin: 4.2.1

Test case

This is the function index.js

const functions = require('firebase-functions')
const admin = require('firebase-admin')

// Initialize Admin with configuration
admin.initializeApp(functions.config().firebase)


exports.fillInitialUserProfile = functions.auth.user().onCreate((event) => {
  const user = event.data
  const db = admin.database()

  return db.ref(`users/${user.uid}`).set({
    displayName: user.displayName || `Member (${user.phoneNumber})`,
    roles: []
  })
})

Steps to reproduce

  • Deploy the functions
  • Remove existing users in the Console so that it starts anew (like a new user being created)
  • Authenticate using Phone number and be sure that login was successful

Were you able to successfully deploy your functions?

There was no error during deployment of the functions

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...
i  functions: packaged functions (931 B) for uploading
✔  functions: functions folder uploaded successfully
i  starting release process (may take several minutes)...
i  functions: updating function fillInitialUserProfile...
✔  functions[fillInitialUserProfile]: Successful update operation. 
✔  functions: all functions deployed successfully!

✔  Deploy complete!

Expected behavior

  • Logs should at least report errors if my function is doing something wrong
  • Under functions Dashboard, the executions count should be incremented to 1.
  • In the database, the users/.../* should be populated for the user

Actual behavior

  • No logs whatsoever recorded
  • Under functions Dashboard, the executions count remains 0.
  • In the database, the users/.../* is empty

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.