繁体   English   中英

如何使用 NodeJS 脚本中的 firebase-tools?

[英]How to use firebase-tools from NodeJS script?

我想从 NodeJS 脚本(而不是从云函数)中删除 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 行上抛出“TypeError:无法在字符串 'easypinger-test' 上创建属性 'project'”。
如果我删除它,它会从删除命令中抛出“TypeError:无法读取未定义的属性‘项目’”。
我怎样才能做到正确?

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

如果您不使用 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
  });

有关使用 firebase-tools 删除集合文档提供了一个可以使用的模板。 如果要指定项目,请注意delete()需要两个参数。 例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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