Amir-Mousavi
Amir-Mousavi

Reputation: 4563

Firebase cloud functions update document with storage public URL

A frontend application is creating documents in firestorm with following model

enter image description here

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.

Upvotes: 1

Views: 573

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50830

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:

batch.commit().then(() => console.log("Document updated"));

However if you just want to update a single document then I would prefer update() instead:

exports.onDocumentCreated = functions.firestore
  .document("db/{docId}")
  .onCreate(async (snapshot, context) => {
    const bucket = firebase.storage().bucket();
    const { fileRef } = <DocumentDataType>snapshot.data();
    const file = bucket.file(fileRef);
    const fileUrl = file.publicUrl();
    
    return snapshot.ref.update({ ...snapshot.data(), fileUrl });
  });

Upvotes: 2

Related Questions