Uploading file to firebase storage via cloud functions - javascript

I am trying to create a cloud function that stores a file into storage. Oringally I had this on the front-end, but have decieded that I need this done as a cloud function. I am struggling with how to do this. my function looks like:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
exports.exampleFunction = functions.https
.onCall((data, context) => {
const someData = {
some1:"abc",
some2: "def"
};
let newKey;
return admin.database()
.ref("/level1/"+data.dataVar1+"/level2/"+data.dataVar2+"/random")
.push(someData)
.then((snapshot)=>{
newKey=snapshot.key;
return admin.database()
.ref("/level1/"+data.dataVar1+"/level2/"+data.dataVar2)
.once("value");
})
.then((snapshot)=>{
const file = data.file;
//Error here
return admin.storage().ref()
.child(snapshot.val().randomVar+"/"+newKey)
.put(file);
})
.catch((error)=>{
console.log(error);
console.log(error.message);
return error;
});
});
However, when I run this I get the following error:
admin.storage(...).ref is not a function
How can I upload the file to storage?

The storage() method returns an instance of Storage class that does not have a ref() method. You need to get reference to the File and then save() it as shown below:
return admin.storage().bucket() // <-- default bucket
.file(snapshot.val().randomVar + "/" + newKey)
.save(file)
.then(() => {
console.log("File uploaded")
return
})
.catch((e) => console.log(e));

Related

How can I remove an entire folder under Storage?

I have a problem deleting my entire folder on firebase storage. I always get a 'storageRef.listAll is not a function' error when I specify the reference to the path. I would like to delete the complete path with all possibly existing images.
const storage = getStorage();
const storageRef = ref(
storage,
`${aktuellerUser._id}/artikelBilder/`
);
storageRef
.listAll()
.then((listResults) => {
const promises = listResults.items.map((item) => {
return item.delete();
});
Promise.all(promises);
})
.catch((error) => {
console.log(error);
});
error TypeError: storageRef.listAll is not a function
You are using the new Firebase Modular SDK where listAll() is a top level function and not a method on StorageReference. Similarly, you need to use deleteObject() to delete a file now instead of .delete() method as shown below:
import {
getStorage,
ref,
listAll,
deleteObject
} from "firebase/storage";
listAll(storageRef)
.then(async (listResults) => {
const promises = listResults.items.map((item) => {
return deleteObject(item);
});
await Promise.all(promises);
})

React Native Firebase: I'm trying to upload profile image via cloud storage but the function in 'then()' is not responding

I'm trying to upload profile picture and for this I'm using firebase cloud storage and firebase real-time database, i've to call another function in then() but it's not working for some reason. Please correct my mistake..
uploadImage = async uri => {
const response = await fetch(uri);
const blob = await response.blob();
var FilePath = imageId + '.' + this.state.currentFileType;
storage()
.ref('user/' + userid + './img')
.child(FilePath)
.put(blob)
.then(snap => {
snap.ref.getDownloadURL().then(downloadURL => {
console.log(downloadURL);
this.processUpload(downloadURL);
});
})
.catch(err => {
console.error(err);
});
};
With catch callback, I'm getting this
[TypeError: undefined is not an object (evaluating
'snap.ref.getDownloadURL')]

Cloud Function to export new documents from Firestore to GCP bucket

I am trying to write a cloud function to export only the new documents getting added to my 'reviews' sub-collection. The trigger for this cloud function is: Cloud Firestore. However, my cloud function deployment fails through the console. Could someone please help me understand what's wrong with my cloud function?
Error message:
Deployment failure:
Build failed: /workspace/index.js:26
}
^
SyntaxError: missing ) after argument list
at new Script (vm.js:83:7)
at checkScriptSyntax (internal/bootstrap/node.js:620:5)
at startup (internal/bootstrap/node.js:280:11)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3); Error ID: d984e68f
Cloud function code:
const firestore = require('#google-cloud/firestore');
const client = new firestore.v1.FirestoreAdminClient();
const bucket = 'gs://bucket_name'
exports.scheduledFirestoreBackup = (event, context) => {
const databaseName = client.databasePath(
// process.env.GCLOUD_PROJECT,
"fs124",
'(default)'
);
return client
.exportDocuments({
name: databaseName,
outputUriPrefix: bucket,
collectionIds: ['reviews'],
})
.onSnapshot()
.then(snap => {
snap.forEach(doc => {
const response = doc.data();
console.log(doc.data());
return response;
}
});
Console snippet:
The message you are getting, SyntaxError: missing ) after argument list is pretty clear. You are missing the closing curly bracket} and parenthesis) of then(). It should look something like this:
const firestore = require('#google-cloud/firestore');
const client = new firestore.v1.FirestoreAdminClient();
const bucket = 'gs://bucket_name'
exports.scheduledFirestoreBackup = (event, context) => {
const databaseName = client.databasePath(
// process.env.GCLOUD_PROJECT,
"fs124",
'(default)'
);
return client
.exportDocuments({
name: databaseName,
outputUriPrefix: bucket,
collectionIds: ['reviews'],
})
.onSnapshot()
.then(snap => {
snap.forEach(doc => {
const response = doc.data();
console.log(doc.data());
return response;
});
});
};

firebase storage, retrieving an image to a vue app

I am trying to download an image from my firebase storage to render it in my Vue app, the upload from the application to the firebase storage is successful, however upon retrieval it gives me an error, i am using the firebase SDK in a Vue CLI 3 setup and vuex to manage my state. Here is the function setting in my actions in the main store.js file
createMeetUp({commit, getters}, payload) {
//here my payload is an object contains the following props
const meetup = {
title: payload.title,
location: payload.location,
date: payload.date.toISOString(),
description: payload.description,
creatorId: getters.user.id
}
let imageUrl
let key
//now i am reaching out to the firebase database to store the above object
firebase.database().ref('meetup').push(meetup)
.then(data => {
key = data.key
return key
})
.then(key => {
//also in my payload object i stored an image file
//so here i am uploading the image to the firebase storage
const fileName = payload.image.name
const extension = fileName.slice(fileName.lastIndexOf('.'))
return firebase.storage().ref('meetup/' + key + '.' + extension).put(payload.image)
})
.then(imageInfo => {
//the issue is here in this then() block as i am stuck on how to retrieve the image from the storage to render it in the app
imageUrl = imageInfo.getDownloadURL()
return firebase.database().ref('meetups').child(key).update({
imageUrl: imageUrl
})
})
.then(() => {
//here i am simply commiting my mutation..
commit('createMeetUp', {
...meetup,
imageUrl: imageUrl,
id : key
})
})
.catch(err => console.log(err))
}
the error I am getting is:
TypeError: imageInfo.getDownloadURL is not a function
Again I believe the issue is in the then() block where I retrieve the image from the firebase storage.
thanks in advance
Following the comments above, the following should work if I am not mistaking (not tested...).
Note that getDownloadURL() returns a promise (see here), therefore you have to chain the promises.
....
.then(key => {
//also in my payload object i stored an image file
//so here i am uploading the image to the firebase storage
const fileName = payload.image.name
const extension = fileName.slice(fileName.lastIndexOf('.'))
return firebase.storage().ref('meetup/' + key + '.' + extension).put(payload.image)
})
.then(uploadTaskSnapshot => {
return uploadTaskSnapshot.ref.getDownloadURL()
})
.then(imageUrl => {
return firebase.database().ref('meetups').child(key).update({
imageUrl: imageUrl
})
})
....

Remove node from Firebase with Functions

I'm trying to remove a node from Firebase using cronjob and i have this function but when it gets executed I get an error saying "Error: could not handle the request" and the log says: "database is not defined"
This is my function:
exports.cleanStatsOnRequest = functions.https.onRequest((req, res) => {
const ref1 = firebase.database.ref;
const dbref = ref1.child(`/dailystats`);
console.log('removing dailystats');
return dbref.remove
.then(() => {
res.send('dailystats removed');
})
.catch(error => {
res.send(error);
});
});
What am I doing wrong? What is the right way to define the database?
You need to use the Firebase Admin SDK to access the Realtime Database from an HTTP trigger Cloud Function. This documentation shows you how to read from the database. This example shows writing to the database, which would be similar to deleting.
Try this. database,ref and remove are functions. Read this guide.
Also you should not return dbref.remove() as remove() will return a promise.
exports.cleanStatsOnRequest = functions.https.onRequest((req, res) => {
const ref1 = firebase.database().ref(); // changes here
const dbref = ref1.child('/dailystats');
console.log('removing dailystats');
return dbref.remove() // changes here
.then(() => {
res.send('dailystats removed');
})
.catch(error => {
res.send(error);
});
});

Categories

Resources