Last active
June 6, 2021 06:09
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Typescript version using
uuid
package: