使用 Cloud Functions for Firebase 和 @google-cloud/storage 删除图像时出现问题 [英] issues deleting an image using Cloud Functions for Firebase and @google-cloud/storage

查看:23
本文介绍了使用 Cloud Functions for Firebase 和 @google-cloud/storage 删除图像时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Cloud Functions for Firebase 中创建一个脚本,该脚本将对 db 事件做出反应并删除其路径位于参数之一(fullPath")中的图像.

I'm trying to create a script in Cloud Functions for Firebase that will react to a db event and remove an image that has its path in one of the params ("fullPath").

这是我正在使用的代码:

this is the code i'm using:

'use strict';

const functions = require('firebase-functions');
const request = require('request-promise');
const admin = require('firebase-admin');
const gcs = require('@google-cloud/storage')({
    projectId: 'XXXXXXX',
    credentials: {
        // removed actual credentials from here
    }});

admin.initializeApp(functions.config().firebase);

// Deletes the user data in the Realtime Datastore when the accounts are deleted.
exports.removeImageOnNodeRemoval = functions.database
    .ref("images/{imageId}")
    .onWrite(function (event) {

        // exit if we are creating a new record (when no previous data exists)
        if (!event.data.previous.exists()) {
            console.log("a new image added");
            return;
        }

        // exit if we are just trying to update the image
        if (event.data.exists()) {
            console.log("image is been modified");
            return;
        }

        let previousData = event.data.previous.val();
        if(!previousData || !previousData.fullPath){
            console.log("no data in the previous");
            return;
        }

        let bucketName = 'XXXXXXX';
        console.log("default bucketName", gcs.bucket(bucketName));
        let file = gcs.bucket(bucketName).file(previousData.fullPath);
        console.log('the file /'+previousData.fullPath, file);

        file.exists().then(function(data) {
            let exists = data[0];
            console.info("file exists", exists);
        });

        file.delete().then(function() {
            // File deleted successfully
            console.log("image removed from project", previousData.fullPath);

        }).catch(function(error) {
            // Uh-oh, an error occurred!
            console.error("failed removing image from project", error, previousData);
        });

    });

我得到的错误:

failed removing image from project { ApiError: Not Found
    at Object.parseHttpRespBody (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:192:30)
    at Object.handleResp (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:132:18)
    at /user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:465:12
    at Request.onResponse [as _callback] (/user_code/node_modules/@google-cloud/storage/node_modules/retry-request/index.js:120:7)
    at Request.self.callback (/user_code/node_modules/@google-cloud/storage/node_modules/request/request.js:188:22)
    at emitTwo (events.js:106:13)
    at Request.emit (events.js:191:7)
    at Request.<anonymous> (/user_code/node_modules/@google-cloud/storage/node_modules/request/request.js:1171:10)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:188:7)
    at IncomingMessage.<anonymous> (/user_code/node_modules/@google-cloud/storage/node_modules/request/request.js:1091:12)
    at IncomingMessage.g (events.js:291:16)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)
  code: 404,
  errors: [ { domain: 'global', reason: 'notFound', message: 'Not Found' } ],
  response: undefined,
  message: 'Not Found' } { contentType: 'image/png',
  fullPath: 'images/1491162408464hznsjdt6oaqtqmukrzfr.png',
  name: '1491162408464hznsjdt6oaqtqmukrzfr.png',
  size: '44.0 KB',
  timeCreated: '2017-04-02T19:46:48.855Z',
  updated: '2017-04-02T19:46:48.855Z' }

我尝试过使用和不使用 google-cloud/storage 的凭据(认为当我在 firebase.functions 中时它们可能会自动填充 - 我需要它们吗?).我尝试在文件路径中添加斜杠.我已经验证该文件实际上存在于存储桶中(即使 file.exists() 返回 false).我提供的凭据适用于我创建的具有存储服务管理员权限的 iam.

i have tried with and without credentials to google-cloud/storage (thinking they might get auto filled while im in firebase.functions - do i need them?). i have tried adding a slash to the file's path. i have validated that the file actually exists in the bucket (even tho file.exists() returns false). the credentials i provided are for an iam i created with admin privileges for the storage service.

我还在免费计划中启用了结算帐户.

i have also enable the billing account on the free plan.

有什么想法吗?

推荐答案

好的,所以我解决了这个问题.这是我的结论:

ok, so i got this solved. here are my conclusions:

  • 您需要将.appspot.com"名称添加到您的存储桶中.它没有写在文档中的任何地方,并且对于不熟悉谷歌云的人来说,在 firebase 中获取您的存储桶名称已经足够困难了.我希望他们能在他们的文档中添加这些简单的信息,或者明确说明您的存储桶在 firebase 中的名称是什么.
  • 使用环境变量 process.env.GCLOUD_PROJECT,它的项目 ID 应该与 Firebase 中的存储桶 ID 相同.再次提醒,记得添加 .appspot.com 后缀.
  • 关于 GCS 的凭据,您在使用 Firebase 的云功能时无需提供这些凭据.您似乎已经通过了身份验证.
  • you need to add to your buckets name the ".appspot.com". Its not written anywhere in the docs and getting your bucket name in firebase is hard enough for someone that is not familiar in the google cloud. I hope they will add this little peace of information into their docs or make it clear what is your bucket's name in firebase.
  • use the environment variable process.env.GCLOUD_PROJECT, it should have your project id that is identical to your bucket id in firebase. again, remember to add the .appspot.com suffix to it.
  • regarding the credentials to GCS, you don't need to provide them when using cloud functions for firebase. you seem to be authenticated already.

这篇关于使用 Cloud Functions for Firebase 和 @google-cloud/storage 删除图像时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆