Firebase 云功能使用存储公共 URL 更新文档
前端应用程序正在 firestorm 中使用以下模型创建文档
fileRef 是字符串:“gs://bucket-location/folder/fileName.extention”
创建后,我想获取文件的公共 URL 并使用该 URL 更新文档
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
const firebase = admin.initializeApp();
interface DocumentDataType {
fileRef: string;
fileType: "image" | "video";
fileUrl: string;
timestamp: FirebaseFirestore.Timestamp;
location: FirebaseFirestore.GeoPoint;
}
exports.onDocumentCreated = functions.firestore
.document("db/{docId}")
.onCreate((snapshot, context) => {
const bucket = firebase.storage().bucket();
const { fileRef } = <DocumentDataType>snapshot.data();
const file = bucket.file(fileRef);
const fileUrl = file.publicUrl();
const batch = admin.firestore().batch();
batch.update(snapshot.ref, { ...snapshot.data(), fileUrl });
});
函数被触发,但文件 URL 不更新。
- 这是将文件存储到云存储中的正确方法吗? -
- SDK v9 更新是否批量更新?我真的很困惑阅读文档,找不到合适的解决方案。
A frontend application is creating documents in firestorm with following model
fileRef is string : "gs://bucket-location/folder/fileName.extention"
Now after creation I want to get the public URL of the file and update the document with the URL
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
const firebase = admin.initializeApp();
interface DocumentDataType {
fileRef: string;
fileType: "image" | "video";
fileUrl: string;
timestamp: FirebaseFirestore.Timestamp;
location: FirebaseFirestore.GeoPoint;
}
exports.onDocumentCreated = functions.firestore
.document("db/{docId}")
.onCreate((snapshot, context) => {
const bucket = firebase.storage().bucket();
const { fileRef } = <DocumentDataType>snapshot.data();
const file = bucket.file(fileRef);
const fileUrl = file.publicUrl();
const batch = admin.firestore().batch();
batch.update(snapshot.ref, { ...snapshot.data(), fileUrl });
});
The functions get triggered but the file URL does not update.
- is it the right approach for getting the file in cloud storage? -
- and also does SDK v9 update is with batch? I really got confused reading the documentation and could not find a proper solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您尝试添加/更新/删除多个文档并希望确保所有操作通过或失败时,批量写入非常有用。在提供的代码中,您没有提交批次。使用
commit()
应该更新文档:但是,如果您只想更新单个文档,那么我更喜欢
update()
:Batched writes are useful when you are trying to add/update/delete multiple documents and want to ensure all the operations either pass or fail. In the provided code you are not commiting the batch. Using
commit()
should update the document:However if you just want to update a single document then I would prefer
update()
instead: