简体   繁体   English

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

[英]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).我想从 NodeJS 脚本(而不是从云函数)中删除 Firestore 集合及其子集合。 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:明确地说,我想执行与此 CLI 命令相同的操作,但要从脚本执行:

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.它在 firebaseTools.use 行上抛出“TypeError:无法在字符串 'easypinger-test' 上创建属性 'project'”。
If I remove it, its throws "TypeError: Cannot read property 'project' of undefined" from the delete command.如果我删除它,它会从删除命令中抛出“TypeError:无法读取未定义的属性‘项目’”。
How can I make it right?我怎样才能做到正确?

The example given on the firebase website works if you're running within a firebase function.如果您在 firebase 函数中运行,则firebase 网站上给出的示例有效。

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 .如果您不使用 firebase 函数,则不必依赖firebase-functions包来检索有效的令牌functions.config().fb.token

For example you could use the firebase-admin package instead.例如,您可以改用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
  });

The documentation on deleting collections with firebase-tools provides a template to work with. 有关使用 firebase-tools 删除集合文档提供了一个可以使用的模板。 If you want to specify a project, note that delete() takes two parameters.如果要指定项目,请注意delete()需要两个参数。 For example:例如:

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