Skip to content

Instantly share code, notes, and snippets.

@EECOLOR
Created August 30, 2017 11:11
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EECOLOR/c3079a59ceab9ab00bac6bfbf15047b2 to your computer and use it in GitHub Desktop.
Save EECOLOR/c3079a59ceab9ab00bac6bfbf15047b2 to your computer and use it in GitHub Desktop.
Saves a file to Firebase storage with token authentication as if created from the console.
const storage = require('@google-cloud/storage')
const createUuid = require("uuid-v4")
const credentials = require('./test-firebase-credentials.json')
const firebaseProjectName = 'test'
const bucketName = `${firebaseProjectName}.appspot.com`
const bucket = storage({ credentials }).bucket(bucketName)
module.exports = firebaseSaveFile
function firebaseSaveFile(fileName, contentType, data) {
const file = bucket.file(fileName)
return file.getMetadata().catch(e => [])
.then(([m]) => ((m || {}).metadata || {}).firebaseStorageDownloadTokens)
.then((token = createUuid()) => file.save(data, { validation: 'md5', resumable: false, metadata: { contentType, metadata: { firebaseStorageDownloadTokens: token } } }).then(_ => token))
.then(token => getDownloadUrl(fileName, token))
}
function getDownloadUrl(fileName, token) { return `https://firebasestorage.googleapis.com/v0/b/${bucketName}/o/${fileName}?alt=media&token=${token}` }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment