所以我有一个使用nodeJS编写的firestore触发函数,当删除firestore中的文档时,我还想删除存储在Firebase存储中的图像,存储中文件的名称与删除的文档ID相同。这是我的功能:
const functions = require('firebase-functions')
// initialize firestore database
const admin = require("../utilities/firebase_admin_init")
const db = admin.firestore()
const storage = admin.storage()
// firestore reference
const eventRef = db.collection('events')
exports.firestoreDeleteEventCleanUp = functions.firestore.document('events/{eventId}').onDelete((snapshot,context) => {
const eventID = context.params.eventId
// how to delete the image in firebase storage in here ????
})
和管理员初始化
const admin = require("firebase-admin")
const functions = require('firebase-functions')
admin.initializeApp(functions.config().firebase)
module.exports = admin
在Android中,我可以执行此操作以删除存储中的图片
// Create a storage reference from our app
val storageRef = storage.reference
// Create a reference to the file to delete
val desertRef = storageRef.child("images/desert.jpg")
// Delete the file
desertRef.delete().addOnSuccessListener {
// File deleted successfully
}.addOnFailureListener {
// Uh-oh, an error occurred!
}
但是现在我正在使用admin SDK,但我不知道如何使用admin SDK删除该文件。我试图在这里https://firebase.google.com/docs/storage/admin/start中阅读文档。但我不知道该如何删除Firebase存储中的图像,如下面的图像
如果使用Firestore触发器,则与storageRef.child("images/desert.jpg")
等效吗?
答案 0 :(得分:2)
如您所参考的文档item中所述,“ Firebase Admin SDK依赖于Google Cloud Storage客户端库来提供Cloud Storage访问。”您应该使用Node.js Client Google Cloud Storage。
尤其是,您需要使用bucket()
的Storage
方法和delete()
的File
方法,如下所示:
const functions = require('firebase-functions')
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore() // <- actually this is not needed for the CF below
const storage = admin.storage()
exports.firestoreDeleteEventCleanUp = functions.firestore.document('events/{eventId}').onDelete((snapshot,context) => {
const eventID = context.params.eventId
const defaultBucket = storage.bucket();
const file = defaultBucket.file("eventThumbnail/" + eventID);
return file.delete();
});