How to properly exit firebase-admin nodejs script when all transaction is completed
Asked Answered
V

3

24

Is there anyway to check if all firebase transaction is completed in firebase-admin nodejs script, and properly disconnect from firebase and exit the nodejs script?

Currently, the firebase-admin nodejs script will just keep running even after all the transaction has been completed.

Valiant answered 13/1, 2017 at 8:43 Comment(0)
O
38

If you're keeping track of all the promises and they complete successfully, what's happening is that the app is keeping a connection open, you can kill the app, by using:

app.delete()

For example if you used the default app you can do this:

firebase.app().delete()
Overblouse answered 22/6, 2017 at 13:16 Comment(2)
this is the real answer. process.exit() isn't the best way to shutdown a node process.Tumblebug
Use admin.app().delete() if you only use firebase-adminPoker
G
6

The DatabaseReference.transaction() method returns a promise which is fulfilled when the transaction is completed. You can use Promise.all() method to wait for any number of these transaction promises to complete and then call process.exit() to end the program.

Here is a full example:

    var admin = require("firebase-admin");

    // Initialize the SDK
    var serviceAccount = require("path/to/serviceAccountKey.json");
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
    });

    // Create two transactions
    var addRef = admin.database().ref("add");
    var addPromise = addRef.transaction(function(current) {
      return (current || 0) + 1;
    });

    var subtractRef = admin.database().ref("subtract");
    var subtractPromise = subtractRef.transaction(function(current) {
      return (current || 0) - 1;
    });

    // Wait for all transactions to complete and then exit
    return Promise.all([addPromise, subtractPromise])
      .then(function() {
        console.log("Transaction promises completed! Exiting...");
        process.exit(0);
      })
      .catch(function(error) {
        console.log("Transactions failed:", error);
        process.exit(1);
      });
Gold answered 25/1, 2017 at 19:44 Comment(0)
O
0

You can terminates the Firestore client and closes all open connections using:

db.terminate()
Orlan answered 24/4, 2024 at 13:39 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.