简体   繁体   English

使用Cloud Functions for Firebase和@ google-cloud / storage删除图像时出现问题

[英]issues deleting an image using Cloud Functions for Firebase and @google-cloud/storage

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"). 我正在尝试在Cloud Functions for Firebase中创建一个脚本,该脚本将对db事件做出反应并删除在其中一个参数(“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);
        });

    });

the error i'm getting: 我得到的错误:

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' }

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?). 我已尝试使用和不使用凭据进行谷歌云/存储(认为他们可能会在我的firebase.functions中自动填充 - 我需要它们吗?)。 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). 我已经验证了文件实际存在于存储桶中(即使file.exists()返回false)。 the credentials i provided are for an iam i created with admin privileges for the storage service. 我提供的凭据是针对我使用存储服务的管理员权限创建的iam。

i have also enable the billing account on the free plan. 我还在免费计划上启用了结算帐户。

any ideas? 有任何想法吗?

ok, so i got this solved. 好的,所以我解决了这个问题。 here are my conclusions: 这是我的结论:

  • you need to add to your buckets name the ".appspot.com". 你需要添加到你的桶名称“.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. 它没有写在文档中的任何地方,并且在firebase中获取您的存储桶名称对于谷歌云中不熟悉的人来说已经够难了。 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. 我希望他们能将这些小小的信息添加到他们的文档中,或者明确说明你在firebase中的名字是什么。
  • use the environment variable process.env.GCLOUD_PROJECT , it should have your project id that is identical to your bucket id in firebase. 使用环境变量process.env.GCLOUD_PROJECT ,它应该具有与firebase中的存储桶ID相同的项目ID。 again, remember to add the .appspot.com suffix to it. 再次,记得添加.appspot.com后缀。
  • regarding the credentials to GCS, you don't need to provide them when using cloud functions for firebase. 关于GCS的凭据,在使用firebase的云功能时,您无需提供它们。 you seem to be authenticated already. 你好像已经被认证了。

Make sure your bucket name doesn't include gs:// 确保您的存储桶名称包含gs://

Eg. 例如。 instead of gs://my-project-id.appspot.com use my-project-id.appspot.com 而不是gs://my-project-id.appspot.com使用my-project-id.appspot.com

let bucket = gcs.bucket('my-project-id.appspot.com')

This may happen to you ( as it did to me ) if you copy your bucket name from, for instance, Android code, where you can use full URL to connect with storage, ie. 这可能发生在你身上( 因为它没有给我 )如果从复制你的水桶的名字,例如,Android的代码,在那里你可以使用完整的URL与存储连接,即。 storage.getReferenceFromUrl('gs://my-proj...

.

Also, it seems the projectId variable you use to initialise gcs doesn't need the appspot.com suffix (but it shouldn't break if you have it included). 此外,似乎用于初始化gcsprojectId变量不需要appspot.com后缀(但如果包含它,则不应该中断)。 Ie. IE浏览器。 projectId:'my-project-id' should be suffice. projectId:'my-project-id'应该足够了。

Lastly, the GCS node package docs states you need to generate separate JSON to pass as keyFilename to test things locally. 最后, GCS节点包文档声明您需要生成单独的JSON以作为keyFilename传递以在本地测试事物。 Good news is - you can use the Firebase Admin SDK key, as described in the Get Started Server/Admin docs instead. 好消息是 - 您可以使用Firebase Admin SDK密钥,如“入门服务器/管理员”文档中所述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 google-cloud 和 node js 从 firebase 存储中检索图像并将其显示在网页上 - how to retrieve image from firebase storage and display it on a webpage using google-cloud and node js 使用 Cloud Functions 将图像上传到 Google Storage - Uploading an image to Google Storage using Cloud Functions 开玩笑 mocking 谷歌云/存储 typescript - Jest mocking google-cloud/storage typescript 无法使用Firebase功能删除Google Cloud Storage文件 - Cannot delete Google Cloud Storage files using Firebase Functions 用于导出 Firestore 备份数据的云功能。 使用 firebase-admin 还是 @google-cloud/firestore? - Cloud function to export Firestore backup data. Using firebase-admin or @google-cloud/firestore? 导入 @google-cloud/storage 部署时 p-limit lib 出错 firebase function - Error in p-limit lib when importing @google-cloud/storage to deploy firebase function Multer Memory 存储到@google-cloud/storage 未完成 - Multer Memory Storage to @google-cloud/storage doesn't complete 从 REST API 获取图像并将其上传到 Firebase 云存储使用 Z035489FF8D324159ZEEA 功能 Cloud Storage - Getting image from REST API and uploading it to Firebase Cloud Storage using Firebase Cloud Functions 通过Nodejs Firebase函数删除文件Google Cloud Storage时出现FetchError - FetchError while deleting files Google Cloud Storage via Nodejs Firebase functions 在 google-cloud/storage 中替代 AWS 的 bucket.putObject() 方法 - Alternative to AWS' bucket.putObject() method in google-cloud/storage
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM