Skip to content

Instantly share code, notes, and snippets.

@torresalmonte
Last active June 6, 2021 06:09
Show Gist options
  • Save torresalmonte/7bd888ff0b27fd741faf29d473ecb079 to your computer and use it in GitHub Desktop.
Save torresalmonte/7bd888ff0b27fd741faf29d473ecb079 to your computer and use it in GitHub Desktop.
Script to get the downloadURL via Admin SDK; if the Firebase metadata required doesn't exists, it adds it
const admin = require('firebase-admin');
const createUuid = require('uuid-v4');
// assumes the existance of the GOOGLE_APPLICATION_CREDENCIAL env variable
admin.initializeApp({
credential: admin.credential.applicationDefault(),
storageBucket: '<YOUR_STORAGE_BUCKET>.appspot.com'
});
// it will get the list of files under "images" and create a downloadUrl for each one
const storage = admin.storage();
storage.bucket().getFiles({prefix: "images"})
.then(([files]) => {
files.forEach(async file => {
let url = await getDownloadURL(file);
console.log(url);
});
})
.catch(err => {
console.error(err);
});
// methods
// build the downloadURL using the file infomation; adds the download token if it doesn't exists
async function getDownloadURL (fileRef) {
const bucket = fileRef.bucket.name;
const [metadata] = await fileRef.getMetadata();
let downloadToken;
if (!metadata.metadata) {
console.log("NO");
downloadToken = await setFirebaseMetadata(fileRef);
} else {
console.log("YES");
downloadToken = metadata.metadata.firebaseStorageDownloadTokens.split(',')[0];
}
let url = `https://firebasestorage.googleapis.com/v0/b/${bucket}/o/${encodeURIComponent(fileRef.name)}?alt=media&token=${downloadToken}`;
return url;
} // getDownloadURL
// set the Firebase metadata with the downloadToken
async function setFirebaseMetadata (fileRef) {
let downloadToken = createUuid();
const metadata = {
metadata: {
firebaseStorageDownloadTokens: downloadToken
}
};
let [response] = await fileRef.setMetadata(metadata);
return downloadToken;
} // setFirebaseMetadata
@crtl
Copy link

crtl commented Jul 10, 2020

Typescript version using uuid package:

// getDownloadUrl.ts


import {v4 as uuidv4} from "uuid";
import {File} from "@google-cloud/storage";

export async function getDownloadURL (fileRef: File): Promise<string> {
    const bucket = fileRef.bucket.name;
    const [metadata] = await fileRef.getMetadata();
    let downloadToken;

    if (!metadata.metadata) {
        downloadToken = await setFirebaseMetadata(fileRef);
    } else {
        downloadToken = metadata.metadata.firebaseStorageDownloadTokens.split(',')[0];
    }

    return `https://firebasestorage.googleapis.com/v0/b/${bucket}/o/${encodeURIComponent(fileRef.name)}?alt=media&token=${downloadToken}`;
} // getDownloadURL

// set the Firebase metadata with the downloadToken
async function setFirebaseMetadata (fileRef: File): Promise<string> {
    const downloadToken = uuidv4();
    
    const metadata = {
        metadata: {
            firebaseStorageDownloadTokens: downloadToken
        }
    };

    await fileRef.setMetadata(metadata);

    return downloadToken;
} // setFirebaseMetadata

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment