thiagopnobre
thiagopnobre

Reputation: 13

Firebase cloud function always getting null snapshot

I'm experiencing some problems while testing my firebase cloud function in the interactive shell (firebase experimental:functions:shell). Within the onWrite event, event.data.val() returns null when I first call it, instead of returning the information I expect. Also, after that, it's not automatically called again after I change some data through a mobile app.

Here is a sample code:

"use strict";

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

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

exports.syncMySql = functions.database.ref('/something/{user_token}/{something_id/}')
  .onWrite(event => {
    const snapshot = event.data.val();
    const user_token = event.params.user_token;
    const mock_id = event.params.something_id;

    console.log(functions.config());
    console.log('# User: ' + user_token + ',\n# Something: ' + something_id + ',\n# Snapshot: ' + snapshot +  '\n Evento: ' + JSON.stringify(event));

    return;
});

And here is a sample of how I'm trying to call it from firebase experimental:functions:shell:

syncMySql('', {params: {user_token: 'sOmEUseRtoKen1234-i_', something_id: '456789'}})

Any ideas on what am I doing wrong? Also, what is this first parameter called in syncMySql? What's it's purpose?

Upvotes: 1

Views: 608

Answers (1)

Scarygami
Scarygami

Reputation: 15569

For invoking functions via the test environment like this, you need to actually provide the data that was supposedly written to the DB yourself. event.data.val() won't read the data from an exising entitity based on the params, but will only return the information you passed in the first parameter of the function call.

For invoking onWrite and onUpdate functions you need to provide the data in the form {before: 'old_data', after: 'new_data' }, where old_data and new_data can be primitives and/or objects, i.e. anything you would write to your DB.

So your full call should be something like this:

syncMySql(
  {
    before: null,
    after: 'something'
  },
  {params: {user_token: 'sOmEUseRtoKen1234-i_', something_id: '456789'}}
);

In this case event.data.val() should return 'something'.

Upvotes: 2

Related Questions