如何从 NodeJS 脚本使用 firebase-tools?

How to use firebase-tools from NodeJS script?

我想从 NodeJS 脚本(而不是 Cloud Function)中删除 Firestore 集合及其子集合。我无法正确选择项目。

明确地说,我想执行与此 CLI 命令相同的操作,但是来自脚本:

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

这是我的尝试:

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");

它在 firebaseTools.use 行抛出“类型错误:无法在字符串 'easypinger-test' 上创建 属性 'project'”。
如果我删除它,它会从删除命令中抛出“类型错误:无法读取未定义的 属性 'project'”。
我怎样才能正确?

documentation on deleting collections with firebase-tools 提供了一个模板供您使用。如果要指定项目,请注意 delete() 有两个参数。例如:

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

如果您 运行 在 firebase 函数中,firebase website 上给出的示例有效。

如果您不使用 firebase 函数,则不必依赖 firebase-functions 包来获取有效令牌 functions.config().fb.token

例如,您可以改用 firebase-admin 包。

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
  });