Reputation: 435
I'm building an app where users can upload an image. I use firebase as the backend. Now since all logged-in users can upload, how do can I manage this safely? The image is uploaded via firebase storage and then the URL is saved to Firestore. I have two options in mind:
I do use firebase cloud functions but if I add the document first the cloud functions are invoked while the image may not be done uploading. What is the best way to tackle this problem?
Upvotes: 0
Views: 176
Reputation: 93
You could set up a user auth claim like "can_upload_pics" then check this claim whenever the user initiates an upload, you might want to use firebase functions to add custom claims. If done right the second option will work as expected checkout this video for a good explanation and example for custom claims
Upvotes: 0
Reputation: 138979
If you thought you can add to a batch operation, a Firestore addition operation, and a Firebase Storage file upload operation and be sure that both are complete, so you can have consistent data, please note that this is not possible. These operations are a part of different Firebase services and unfortunately, at the moment I'm writing this answer there is no way you can make them atomic.
As far as I know, none of the Firebase products support cross-product transactional operations. To solve this, you'll have to nest the calls during your addition/upload operations and handle the error if the second operation fails. This means that you either have to delete the document from Firestore if the upload operation in Cloud Storage fails or vice versa.
But note, at some point in time, there will be a failure that the client can't roll back one of the delete operations. The most common approach for these inevitable failures that might happen, is to make your code robust by handling exceptions and performing occasional cleanups in both places, Firestore, and Firebase Storage.
Upvotes: 2