Change Firebase data coming from angularfire2 - firebase

I have a database which stores a node like this:
-KdFlSK9eqzRDPd_I71I
address:
heats:
image: 2017-02-18T10:30:15.025Z.jpeg
title:
Inside the image tag, there is the filename of a file stored in Firebase Storage. What I would like to do is get the full path to get the file from Firebase Storage before 2017-02-18T10:30:15.025Z.jpeg is inserted inside the image source. So basically, alter the data before render.
[Answer]
Very simple - I did not change the data from firebase, I simple set the new data to a new variable which doesn't show if not set.

You can do it as shown below.You just need to put downloadURL on your image property after the image has been saved in the firebase storage.
Note: This is just a sample code where I used.Please adjust it according to your situation.
takeBillPhoto(billId: string, imageURL: string) {
const storageRef = firebase.storage().ref(this.userId);
return storageRef.child(billId).child('billPicture')
.putString(imageURL, 'base64', { contentType: 'image/png' })
.then(pictureSnapshot => {
this.billList.update(billId, { picture: pictureSnapshot.downloadURL });
});
}

Related

Uploading an image to Firestore. How to read file format before upload

I'm using the expo-image-picker to select an image and then upload it to FireStore
const pickImage=async()=>{
let result=await ImagePicker.launchImageLibraryAsync({
mediaTypes:ImagePicker.MediaTypeOptions.Images,
allowsEditing:true,
aspect:[4,3],
quality:1,
});
if (!result.cancelled){
setSelectedImage(result.uri)
}
}
let Enter = async () => {
const storage=getStorage();
const reference=ref(storage,title+'.png')
const img=await fetch(selectedImage);
const bytes=await img.blob();
await uploadBytes(reference,bytes);
await createEntry(title,descr);
};
The 'pickImage' function lets me pick the image from the computer, the 'Enter' function uploads it, then 'CreateEntry' just creates a seperate document which references the stored image.
Everything works fine except when I declare the reference constant under 'Enter'. If I don't include "+'.png'" after title it just shows up as a text document in Firestore. "+'.png'" is a workaround but obviously this limits me to just uploading pngs. I would like to create a 'documentFormat' variable which I could just add in there so it would look like:
const reference=ref(storage,title+documentFormat) but I can't figure out how to read the format of the selected document.
The ImagePicker.launchImageLibraryAsync method does not return a mime type for the selected file. What you can do is use this helper function to get the file extension and accordingly use it in place.
function get_extension(url: string) {
let extension = url.toLowerCase().split(".").pop();
return extension; // png, mp4, jpeg etc.
}
Usage
const reference = ref(storage, title + get_extension(selectedImage))

Firebase storage | how to update customMetaData with merge true

When uploading a file.. I have set the following custom meta data
const metadata = {
customMetadata: {
user: userId,
disabled: 'false'
},
};
and upload it like
uploadBytes(ref(this.str, invoicePath), invoiceFile, metadata),
Now some time later I would like to set disabled to true. Doing smth like this
const metadata = {
customMetadata: {
disabled: 'true',
},
};
updateMetadata(ref(this.str, invoicePath), metadata)
will remove the user key in the customMetaData
Is it possible to update it without setting the user key again??
As far as I know the metadata you pass always completely replaces the existing metadata for that object. If you want to retain values from the previous metadata, you will have to perform a read-modify-write sequence.
Update: Interestingly enough the documentation on updating metadata says:
You can update file metadata at any time after the file upload completes by using the updateMetadata() method. Refer to the full list for more information on what properties can be updated. Only the properties specified in the metadata are updated, all others are left unmodified. updateMetadata() returns a Promise containing the complete metadata, or an error if the Promise rejects.

Been trying to set Custom time on a file using Firebase?

I'm trying to set the Custom time attribute in firebase on the front end. Everything is possible to set, like contentDisposition, custom Metadata etc, just can't find any way or any info about setting Custom time.
You can see it referenced here https://cloud.google.com/storage/docs/metadata#custom-time
You can set the custom time on the file manually in the Storage cloud console, but even when you do and you load the file in firebase on the front end, it's missing from the returned object! (makes me feel like it's not possible to achieve this)
var storage = this.$firebase.app().storage("gs://my-files");
var storage2 = storage.ref().child(this.file);
//// Tried this
var md = {
customTime: now.$firebase.firestore.FieldValue.serverTimestamp()
};
//// & Tried this
var md = {
Custom-Time: now.$firebase.firestore.FieldValue.serverTimestamp()
};
storage2.updateMetadata(md).then((metadata) => {
console.log(metadata);
}).catch((err) => {
console.log(err);
});
The reason I ask is I'm trying to push back the lifecycle delete date (which will be based on the custom time) every time the file is loaded. Does anyone know the answer or an alternative way of doing it?
Thanks in advance
The CustomTime metadata is not possible to update using Firebase JavaScript SDK since it is not included in the file metadata properties list mentioned in the documentation. So even if you specify it as customTime: or Custom-Time: the updateMetadata() method does not perform any changes.
I suggest you as a better practice, set the CustomTime metadata from the cloud console and modify the CustomTimeBefore Lifecycle condition from the back-end each time you load the file using the addLifeCycleRule method of the GCP Node.js Client.
// Imports the Google Cloud client library
const {Storage} = require('#google-cloud/storage');
// Creates a client
const storage = new Storage();
//Imports your Google Cloud Storage bucket
const myBucket = storage.bucket('my_bucket');
//-
// Delete object that has a customTime before 2021-05-25.
//-
myBucket.addLifecycleRule({
action: 'delete',
condition: {
customTimeBefore: new Date('2021-05-25')
}
}, function(err, apiResponse) {});

Firebase query download the whole database. Why?

I try to download and show only specific data from the Realtime Database. I have the following code:
getUserPlatformIos() {
this.dataRef = this.afDatabase.list('data/users', ref => ref.orderByChild('meta/platform').equalTo('ios'));
this.data = this.dataRef.snapshotChanges().map(changes => {
return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
return this.data;
}
My firebase database structure
Firebase rules
Why firebase does download the whole database if I query before? This causes very long loading times and a lot of downloaded data....
Indexes need to be defined at the place where you the query. Since you run the query on data/users, that's where you need to define your index:
"users": {
".indexOn": "meta/platform"
}
This defines an index on users, which has the value of the meta/platform property of each user.
Note that the log output of your app should be showing an error message with precisely this information. I highly recommend checking log output whenever something doesn't work the way you expect it to work.

Cloud Functions for Firebase: write to database on fileupload

I have a cloud function (modified version of generateThumbnail sample function). I want to create thumbnail, but I also want to get image width and height, and update size value in the database.
To break up this problem:
I need to get snapshot of current database
Navigate to /projects of database
Find correct key using filename (project.src == fileName)
Get size of image (done)
Update project.size to new value
I did some research, but I only found the functions.database.DeltaSnapshot interface, that is given, when you listen on functions.database().ref().onwrite(snapshot => {})
projects.json:
[{
"name": "lolipop",
"src": "lolipop.jpg",
"size": ""
},{
"name": "cookie",
"src": "cookie.jpg",
"size": ""
}]
Database interaction can be done using the firebase-admin package. Check out this sample to see how a function not triggered by a database write accesses the database.
Accessing child nodes by the value of one of their keys in Firebase is a bit clunky, more on that at the end.
For each concern:
1 & 2: create a reference to the projects key in your DB
3: Find the project you're looking for by its src key
5: Update the project
// create reference
const projectsRef = admin.database().ref('projects');
// create query
const srcProjectQuery = projectsRef.orderByChild('src').equalTo(fileName);
// read objects that fit the query
return srcPojectQuery.once('value').then(snapshot => {
const updates = {};
snapshot.forEach(childSnapshot => {
updates[`${childSnapshot.key}/size`] = fileSize;
});
return projectsRef.update(updates);
});
Since it looks like you're treating the src values as unique, a lot of headache can be avoided by using the src as the key for each project object. This would simplify things to:
const projectsRef = admin.database().ref(`projects/${src}`);
projectsRef.update({'size': fileSize});

Resources