【问题标题】:How to include Typescript types for Google cloud storage in firebase cloud functions如何在 Firebase 云功能中包含用于 Google 云存储的 Typescript 类型
【发布时间】:2020-07-23 08:34:19
【问题描述】:

我有一个用 Typescript 编写的 Firebase 云函数,我可以在其中访问 Google 存储桶。

如果我得到这样的桶:

const storageBucket = admin.storage().bucket(storageBucketName);

VScode 显示 storageBucket 的类型为 Bucket。

但如果我尝试将其用作函数的参数:

async function deleteOldBackup(storageBucket: Bucket) {

类型Bucket用红色下划线表示“找不到Bucket”。

如果我尝试像这样导入 Bucket 类型:

import { Bucket, File } from "@google-cloud/storage"

我收到来自管理员的 Bucket 与我的 deleteOldBackup 函数中的 Bucket 不同的错误。

如何在我的 firebase 云函数中为谷歌存储获取适当的 Typescript 类型?

【问题讨论】:

    标签: typescript google-cloud-functions google-cloud-storage


    【解决方案1】:

    将依赖项更新到最新版本即可。

    我有这些并且类型匹配:

    "dependencies": {
      "firebase-admin": "^9.3.0",
      "firebase-functions": "^3.11.0",
      "@google-cloud/storage": "^5.4.0"
    }
    

    【讨论】:

    • 即使这样我们也需要引用类型。所以它们应该以某种方式导出。
    【解决方案2】:

    您必须导入客户端库的方式如下:“const {Storage} = require('@google-cloud/storage');”

    例如,如果您愿意,可以列出存储桶中的对象。你必须使用类似这样的代码:

    /

    **
     * TODO(developer): Uncomment the following line before running the sample.
     */
    // const bucketName = 'Name of a bucket, e.g. my-bucket';
    
    // Imports the Google Cloud client library
    const {Storage} = require('@google-cloud/storage');
    
    // Creates a client
    const storage = new Storage();
    
    async function listFiles() {
      // Lists files in the bucket
      const [files] = await storage.bucket(bucketName).getFiles();
    
      console.log('Files:');
      files.forEach(file => {
        console.log(file.name);
      });
    }
    
    listFiles().catch(console.error);
    

    您可以在link 中找到有关此示例的更多信息,在link 中找到有关客户端库的更多信息。

    【讨论】:

      【解决方案3】:

      嗯……这对我有用:

      import { File } from "@google-cloud/storage";
      
      type GetFileHelperResult = {
        file?: File;
      };
      

      我正在使用:

      "firebase": "8.2.6",
      "firebase-admin": "^9.2.0",
      "firebase-functions": "^3.11.0",
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-12
        • 2021-10-16
        • 1970-01-01
        • 2019-08-08
        • 2017-08-20
        • 2021-04-14
        • 2019-04-16
        • 2017-10-09
        相关资源
        最近更新 更多