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

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

问题描述

我正在尝试在Fire的Cloud Functions中创建一个脚本,该脚本将对db事件作出反应,并删除在其中一个参数(fullPath)中具有其路径的图像。



这是我使用的代码:

 'use strict'; 

const函数= require('firebase-functions');
const request = require('request-promise');
const admin = require('firebase-admin');
const gcs = require('@ google-cloud / storage')({
projectId:'XXXXXXX',
credentials:{
//从这里删除实际凭证
}});

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

//删除账户时删除实时数据存储中的用户数据。
exports.removeImageOnNodeRemoval = functions.database
.ref(images / {imageId})
.onWrite(function(event){

// exit if我们正在创建一个新的记录(当没有以前的数据存在时)
if(!event.data.previous.exists()){
console.log(a new image added);
返回;
}

//退出,如果我们只是想更新图像
if(event.data.exists()){
console.log (image is modified);
return;
}

let previousData = event.data.previous.val();
if(!previousData | |!previousData.fullPath){
console.log(前面没有数据);
return;
}

let bucketName ='XXXXXXX';
console.log(default bucketName,gcs.bucket(bucketName));
let file = gcs.bucket(bucketName).file(previousData.fullPath);
co nsole.log('文件/'+previousData.fullPath,文件);
$ b $ file.exists()。then(function(data){
let exists = data [0];
console.info(file exists,exists);
});
$ b $ file.delete()。then(function(){
//文件已成功删除
console.log(image从项目中移除,previousData.fullPath);

})。catch(function(error){
//呃,发生错误!
console.error(从项目中移除图片失败,error,previousData );
});

});

我得到的错误:

<$删除图像{ApiError:Not Found
at Object.parseHttpRespBody(/ user_code / node_modules / @ google-cloud / storage / node_modules / @ google-cloud / common / p $ p> src / util.js:192:30)
在Object.handleResp(/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:132:18)
位于/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:465:12
位于Request.onResponse [as _callback](/ user_code /node_modules/@google-cloud/storage/node_modules/retry-request/index.js:120:7)
在Request.self.callback(/ user_code / node_modules / @ google-cloud / storage / node_modules / request / request.js:188:22)在请求时,在请求消息(events.js:191:7)上
在emitTwo(events.js:106:13)上

<匿名> (/user_code/node_modules/@google-cloud/storage/node_modules/request/request.js:1171:10)
在emitOne(events.js:96:13)
在Request.emit(events .js:188:7)IncomingMessage
< anonymous> (/user_code/node_modules/@google-cloud/storage/node_modules/request/request.js:1091:12)
IncomingMessage.g(events.js:291:16)
at emitNone(events .js:91:20)
在IncomingMessage.emit(events.js:185:7)
在endReadableNT(_stream_readable.js:974:12)
在_combinedTickCallback(internal / process /
at process._tickDomainCallback(internal / process / next_tick.js:122:9)
code:404,
errors:[{domain:'global' ,原因:'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',
已更新:'2017-04-02T19:46:48.855Z'}

尝试与无凭据谷歌云/存储(瘦国王他们可能会得到自动填充,而我在firebase.functions - 我需要他们吗?)。我已经尝试添加一个斜杠文件的路径。我已经验证文件实际上存在于存储桶中(甚至tho file.exists()返回false)。我提供的凭据是为我创建的存储服务的管理权限。

我也启用计费帐户的免费计划。



有什么想法?

解决方案

好的,我解决了这个问题。这里是我的结论:


  • 您需要将.appspot.com添加到您的存储桶中。它没有写在文档中的任何地方,并获得您的存储桶名称在firebase是很难的人不熟悉的谷歌云。我希望他们能够在文档中加入这些信息,或者在firebase中清楚你的bucket的名字。
  • 使用环境变量process.env.GCLOUD_PROJECT
  • 它应该有你的项目ID是相同的在你的桶ID在firebase。再次,请记住将.appspot.com后缀添加到它。
  • 有关GCS的凭据,您不需要为使用firebase的云功能提供它们。您似乎已经过身份验证。


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

    });

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?). 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.

any ideas?

解决方案

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

  • 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.

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

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