我正在尝试创建一个 Google Cloud Function,它可以删除链接到 Firebase 实时数据库中的 person 对象的图像。但是每次我收到“请求期间出错”错误时(没有任何特定的错误代码,它只是未定义) )..这是一个函数代码:
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
const gcs = require('@google-cloud/storage')({
projectId: "PROJ_ID",
keyFilename: "SERV_ACC.json LOCATED IN FUNCTIONS FOLDER"});
admin.initializeApp(functions.config().firebase);
exports.removePersonImage =
functions.database.ref("users/{userId}/persons/{personId}")
.onDelete((snapshot, context) => {
const person = snapshot.val();
if (!person.photo || !person.photo.key) {
console.log("Person doesn't have photo");
return true;
}
var path = "user/" + context.params.userId + "/" + person.photo.key + ".jpg";
console.log("Bucket path: " + path);
return gcs.bucket(path)
.delete()
.then(() => {
console.log("Image " + person.photo.key + " successfully deleted");
return true;
})
.catch(err => {
console.error("Failed to remove image " + person.photo.key);
console.error("Error: " + err.message);
return false;
});
});
最佳答案
我认为您正在获取带有文件路径的存储桶的引用。
您应该首先创建对存储桶的引用,然后使用存储桶上的 file()
方法来创建 File 对象。
首先根据您在存储控制台中看到的根存储桶名称声明存储桶,但不带 gs://
,如下所示:
const bucket = gcs.bucket("***projectname***.appspot.com");
然后使用“目录”声明您的文件。
const file = bucket.file("user/" + context.params.userId + "/" + person.photo.key + ".jpg");
然后调用删除:
return file.delete()
.then(() => {
....
参见https://cloud.google.com/nodejs/docs/reference/storage/1.7.x/Bucket#file
和https://cloud.google.com/nodejs/docs/reference/storage/1.7.x/Storage#bucket
关于javascript - 通过云功能删除云存储中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50679125/