简体   繁体   中英

How to use firebase-tools from NodeJS script?

I want to delete a Firestore collection and its sub-collections from a NodeJS script (not from a Cloud Function). I cannot get it right with project selection.

To be clear, I want to perform the same as this CLI command, but from a script:

firebase -P my-project firestore:delete fruits --recursive

Here is my attempt:

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

const serviceAccount = require("path_to_my_service_account_key.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: `https://my-project.firebaseio.com`,
});

const firebaseTools = require("firebase-tools");

firebaseTools.use("my-project");

async function deleteCollection(collectionName) {
    const ref = admin.firestore().collection(collectionName);
    const res = await firebaseTools.firestore.delete(ref);
    console.log("delete success:", res);
}

deleteCollection("fruits");

It throws "TypeError: Cannot create property 'project' on string 'easypinger-test'" on the firebaseTools.use line.
If I remove it, its throws "TypeError: Cannot read property 'project' of undefined" from the delete command.
How can I make it right?

The example given on the firebase website works if you're running within a firebase function.

If you are not using firebase functions, you don't have to rely on the firebase-functions package to in order to get retrieve a valid token functions.config().fb.token .

For example you could use the firebase-admin package instead.

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

admin.initializeApp({
  // APP OPTIONS
});

const cred = admin.app().options.credential;
if (!cred) {
  throw new Error('Admin credential was undefined');
}
const access_token = (await cred.getAccessToken()).access_token;

await firebase_tools.firestore
  .delete(path, {
    project: process.env.GCLOUD_PROJECT,
    recursive: true,
    yes: true,
    token: access_token
  });

The documentation on deleting collections with firebase-tools provides a template to work with. If you want to specify a project, note that delete() takes two parameters. For example:

firebase_tools.firestore
    .delete(path, {
        project: YOUR-PROJECT-ID-HERE,
        recursive: true,
        yes: true,
        token: functions.config().fb.token
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM