Chris Jacobs
Chris Jacobs

Reputation: 49

Removing Firebase Realtime Database node using Cloud Function

I can successfully get a query param and post it into my realtime database at a path defined by the query param itself, using this code:

'use strict';

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

exports.emptyHat = functions.https.onRequest(async (req, res) => {
  // Grab the group parameter.
  const group = req.query.group;
  // Push the new message into the Realtime Database using the Firebase Admin SDK.
  const snapshot = await admin.database().ref('/group').push({list: group});
  // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
  res.redirect(303, snapshot.ref.toString());
});

If the query param was 'test', the result would be a new entry at /test/{firebaseID}/{'list':'test'}

When I tried to modify it to remove the node named in the query parameter I get errors. (I'm trying to remove that top level /test node

'use strict';

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


exports.emptyHat = functions.https.onRequest(async (req, res) => {
  // Grab the group parameter.
  const group = req.query.group;
  // Remove the node at the location 'group'.
  functions.database().ref('/group').remove();
  // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
  //res.redirect(303, snapshot.ref.toString());
});

Error message in the logs:

    at exports.emptyHat.functions.https.onRequest (/srv/index.js:95:13)
    at cloudFunction (/srv/node_modules/firebase-functions/lib/providers/https.js:49:9)
    at /worker/worker.js:783:7
    at /worker/worker.js:766:11
    at _combinedTickCallback (internal/process/next_tick.js:132:7)
    at process._tickDomainCallback (internal/process/next_tick.js:219:9)

Upvotes: 0

Views: 400

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317928

Your second function is ignoring the promise returned by the Firebase API. This makes it unlikely to work in Cloud Functions. Cloud Functions HTTP triggers require that you only send a response only after all the asynchronous work is complete. After your function generates a response, it will terminate and clean up any async work still in progress. That work might not complete.

Your second function should be more like your first one, and use the promise returned by remove() and wait for it to complete before sending the response:

exports.emptyHat = functions.https.onRequest(async (req, res) => {
  const group = req.query.group;
  await admin.database().ref('/group').remove();
  // send the response here.
});

Upvotes: 1

Related Questions