Firebase 存储管理错误:400 存储桶名称无效

Pro*_*oWi 1 firebase google-cloud-functions firebase-storage firebase-admin

我正在尝试使用 firebase 函数来维护我的数据库和存储。基本上在过期后将一些旧条目从一个引用/存储桶删除到另一个引用/存储桶。数据库部分工作得很好。然而,存储部分却没有那么多。以下是我初始化代码中所有内容的方法:

var functions = require('firebase-functions');
var admin = require("firebase-admin");
var serviceAccount = require('./my-app-bla-bla.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://my-app.firebaseio.com',
  storageBucket: 'gs://my-app.appspot.com'
});
Run Code Online (Sandbox Code Playgroud)

然后在清理数据库和存储的 cron 作业中,我有以下内容(这只是一些小的相关部分):

const st = admin.storage();

st.bucket("gs://my-app.appspot.com/old-listings/"+listingKey).create(function(error, bucket, apiResponse) {
    if (error) {
        console.log("Couldn't create an OldListing bucket: " + error.code);
        console.log(apiResponse);
    } else {
        console.log("Created OldListing bucket");
    }
});
Run Code Online (Sandbox Code Playgroud)

最后一段代码触发错误并给出以下日志:

Couldn't create an OldListing bucket: 400
{ error: 
   { errors: [ [Object] ],
     code: 400,
     message: 'Invalid bucket name: \'my-app.appspot.com/old-listings/SomeUniqueID\'' } }
Run Code Online (Sandbox Code Playgroud)

因为我是第一次运行此代码,所以该文件夹old-listings尚不存在。所以我想也许我应该首先自己创建它的存储桶。它给了我同样的错误。

我还尝试使用没有 gs 链接的存储桶,例如st.bucket("old-listings/"+listingKey)代替st.bucket("gs://my-app.appspot.com/old-listings/"+listingKey). 仍然给我同样的错误。

那么这里究竟缺少什么?我究竟做错了什么?

编辑1

我尝试在 cron 函数的开头添加以下代码片段。为了更好地了解正在发生的事情。

admin.storage().bucket("my-app.appspot.com").exists(function(error, exists) {
    if (!error) {
        if (exists) {
            console.log("Top Bucket Exists");
        } else {
            console.log("Top Bucket Does Not Exist");
        }
    } else {
        console.log("Top Bucket Error " + error.code);
    }
});

admin.storage().bucket("my-app.appspot.com/listings").exists(function(error, exists) {
    if (!error) {
        if (exists) {
            console.log("Listings Bucket Exists");
        } else {
            console.log("Listings Bucket Does Not Exist");
        }
    } else {
        console.log("Listings Bucket Error " + error.code);
    }
});
Run Code Online (Sandbox Code Playgroud)

我在日志中收到以下内容:

Top Bucket Exists
Listing Bucket Error undefined
Run Code Online (Sandbox Code Playgroud)

当然,listings我的 firebase 存储中已经有一个名为的文件夹。那么到底为什么第二个桶是未定义的呢?

Dou*_*son 5

当您为存储桶构建名称时,它不应包含文件路径组件,它应该只是存储桶的唯一名称 - 所有对象的容器。如果要引用存储桶中的文件,请使用存储桶对象上的file()方法来获取要处理的File对象。

const st = admin.storage();
const bucket = st.bucket('name-of-your-bucket');
const file = bucket.file('name-of-your-file');
Run Code Online (Sandbox Code Playgroud)

  • 云存储中实际上没有任何“目录”。只有一些文件的名称看起来像是包含目录,以帮助您建立文件组织的心理模型。请注意,缺少用于列出“目录”内文件的 API,因为目录不存在。将来可能能够在“目录”中列出文件,但实际上仍然不会有任何目录,只有“目录”概念中的文件的新索引。 (3认同)