Skip to content

Instantly share code, notes, and snippets.

@EECOLOR
Created August 30, 2017 11:11
Show Gist options
  • Select an option

  • Save EECOLOR/c3079a59ceab9ab00bac6bfbf15047b2 to your computer and use it in GitHub Desktop.

Select an option

Save EECOLOR/c3079a59ceab9ab00bac6bfbf15047b2 to your computer and use it in GitHub Desktop.

Revisions

  1. EECOLOR created this gist Aug 30, 2017.
    20 changes: 20 additions & 0 deletions firebaseSaveFile.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    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}` }