从云功能中删除云存储中的文件

时间:2018-06-04 11:05:12

标签: javascript node.js firebase firebase-realtime-database google-cloud-storage

我正在尝试创建一个Google Cloud功能,删除Firebase实时数据库中与person对象关联的图像..但每次我收到“请求时出错”错误(没有任何特定的error.code,它只是未定义) )..这是一个功能代码:

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;
    });
});

1 个答案:

答案 0 :(得分:0)

我认为您正在使用文件路径获取对Bucket的引用。

首先应创建对Bucket的引用,然后使用Bucket上的file()方法创建File对象。

首先根据您在存储控制台中看到但没有gs://的根存储桶名称声明存储桶,如下所示:

const bucket = gcs.bucket("***projectname***.appspot.com");  

然后用子桶声明你的文件(即"目录")

const file = bucket.file("user/" + context.params.userId + "/" + person.photo.key + ".jpg");

然后调用delete:

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