How to call refFromURL in Firebase Cloud Function

Viewed 3132

I'm storing references to files in Firebase Cloud Storage using URLs. In firebase client code, you can call firebase.storage().refFromURL(photo.image) to get the actual storage reference and do handy things like call delete with it. How do I accomplish the same thing in a cloud function (specifically a realtime database trigger)? I want to be able to clean up images after deleting the object that references them.

5 Answers

Following Bob Snider's answer, this is a little function (typescript) to extract file full path from URL.

export const getFileFromURL = (fileURL: string): Promise<any> => {
  const fSlashes = fileURL.split('/');
  const fQuery = fSlashes[fSlashes.length - 1].split('?');
  const segments = fQuery[0].split('%2F');
  const fileName = segments.join('/');

  return fileName;
}

Here is a one-liner.

const refFromURL = (URL) => decodeURIComponent(URL.split('/').pop().split('?')[0])

I've wrote code sample which I using instead refFromURL method from web-firebase in my functions project based on Bob Snyder answer.

function refFromUrl(gsLink) {
    var fileEntryTemp = gsLink.file.replace("gs://", "")
    var bucketName = fileEntryTemp.substring(0, fileEntryTemp.indexOf("/"));
    var filename = gsLink.file.match("gs://" + bucketName + "/" + "(.*)")[1];
    var gsReference = admin.storage().bucket().file(filename);
    return gsReference;
}

Here is an example how I get a download link based on this ref:

var gsReference = refFromUrl(fileEntry);

gsReference.getSignedUrl({
    action: 'read',
    expires: '03-09-2491'
    }).then(function (url) {
    console.log(url);
    response.send(url);
}).catch(function (error) {

});

Hope this will save time for somebody

Related