diff --git a/perf-next/index.js b/perf-next/index.js index 96545d31..58b70ae7 100644 --- a/perf-next/index.js +++ b/perf-next/index.js @@ -10,6 +10,25 @@ const firebaseApp = initializeApp({ }); const perf = getInstance(firebaseApp); +function intialize() { + // [START perf_initialize] + const { initializeApp } = require("firebase/app"); + const { getPerformance } = require("firebase/performance"); + + // TODO: Replace the following with your app's Firebase project configuration + // See: https://firebase.google.com/docs/web/setup#config-object + const firebaseConfig = { + // ... + }; + + // Initialize Firebase + const app = initializeApp(firebaseConfig); + + // Initialize Performance Monitoring and get a reference to the service + const perf = getPerformance(app); + // [END perf_initialize] +} + export function getInstance(firebaseApp) { // [START perf_get_instance] const { getPerformance } = require("firebase/performance"); diff --git a/perf/index.js b/perf/index.js index 9ef0dd9c..6d512e32 100644 --- a/perf/index.js +++ b/perf/index.js @@ -3,6 +3,22 @@ import "firebase/performance"; const perf = firebase.performance(); +function intialize() { + // [START perf_initialize] + // TODO: Replace the following with your app's Firebase project configuration + // See: https://firebase.google.com/docs/web/setup#config-object + var firebaseConfig = { + // ... + }; + + // Initialize Firebase + firebase.initializeApp(firebaseConfig); + + // Initialize Performance Monitoring and get a reference to the service + var perf = firebase.performance(); + // [END perf_initialize] +} + function addCustomTrace() { // [START perf_add_custom_trace] const trace = perf.trace("CUSTOM_TRACE_NAME"); diff --git a/snippets/perf-next/index/perf_initialize.js b/snippets/perf-next/index/perf_initialize.js new file mode 100644 index 00000000..c4802566 --- /dev/null +++ b/snippets/perf-next/index/perf_initialize.js @@ -0,0 +1,21 @@ +// This snippet file was generated by processing the source file: +// ./perf-next/index.js +// +// To make edits to the snippets in this file, please edit the source + +// [START perf_initialize_modular] +import { initializeApp } from "firebase/app"; +import { getPerformance } from "firebase/performance"; + +// TODO: Replace the following with your app's Firebase project configuration +// See: https://firebase.google.com/docs/web/setup#config-object +const firebaseConfig = { + // ... +}; + +// Initialize Firebase +const app = initializeApp(firebaseConfig); + +// Initialize Performance Monitoring and get a reference to the service +const perf = getPerformance(app); +// [END perf_initialize_modular] \ No newline at end of file diff --git a/storage/create-reference.js b/storage/create-reference.js new file mode 100644 index 00000000..09794832 --- /dev/null +++ b/storage/create-reference.js @@ -0,0 +1,95 @@ +import firebase from "firebase/app"; +import "firebase/storage"; + +function createRef() { + // [START storage_create_ref] + // Get a reference to the storage service, which is used to create references in your storage bucket + var storage = firebase.storage(); + + // Create a storage reference from our storage service + var storageRef = storage.ref(); + // [END storage_create_ref] +} + +function createRefChild() { + const storageRef = firebase.storage().ref(); + + // [START storage_create_ref_child] + // Create a child reference + var imagesRef = storageRef.child('images'); + // imagesRef now points to 'images' + + // Child references can also take paths delimited by '/' + var spaceRef = storageRef.child('images/space.jpg'); + // spaceRef now points to "images/space.jpg" + // imagesRef still points to "images" + // [END storage_create_ref_child] +} + +function navigateRef() { + const spaceRef = firebase.storage().ref().child('images/space.jpg'); + + // [START storage_navigate_ref] + // Parent allows us to move to the parent of a reference + var imagesRef = spaceRef.parent; + // imagesRef now points to 'images' + + // Root allows us to move all the way back to the top of our bucket + var rootRef = spaceRef.root; + // rootRef now points to the root + // [END storage_navigate_ref] +} + +function navigateRefChain() { + const spaceRef = firebase.storage().ref().child('images/space.jpg'); + + // [START storage_navigate_ref_chain] + // References can be chained together multiple times + var earthRef = spaceRef.parent.child('earth.jpg'); + // earthRef points to 'images/earth.jpg' + + // nullRef is null, since the parent of root is null + var nullRef = spaceRef.root.parent; + // [END storage_navigate_ref_chain] +} + +function refProperties() { + const spaceRef = firebase.storage().ref().child('images/space.jpg'); + + // [START storage_ref_properties] + // Reference's path is: 'images/space.jpg' + // This is analogous to a file path on disk + spaceRef.fullPath; + + // Reference's name is the last segment of the full path: 'space.jpg' + // This is analogous to the file name + spaceRef.name; + + // Reference's bucket is the name of the storage bucket where files are stored + spaceRef.bucket; + // [END storage_ref_properties] +} + +function refFullExample() { + // [START storage_ref_full_example] + // Points to the root reference + var storageRef = firebase.storage().ref(); + + // Points to 'images' + var imagesRef = storageRef.child('images'); + + // Points to 'images/space.jpg' + // Note that you can use variables to create child values + var fileName = 'space.jpg'; + var spaceRef = imagesRef.child(fileName); + + // File path is 'images/space.jpg' + var path = spaceRef.fullPath; + + // File name is 'space.jpg' + var name = spaceRef.name; + + // Points to 'images' + var imagesRef = spaceRef.parent; + // [END storage_ref_full_example] +} diff --git a/storage/delete-files.js b/storage/delete-files.js new file mode 100644 index 00000000..73b84904 --- /dev/null +++ b/storage/delete-files.js @@ -0,0 +1,18 @@ +import firebase from "firebase/app"; +import "firebase/storage"; + +function deleteFile() { + const storageRef = firebase.storage().ref(); + + // [START storage_delete_file] + // Create a reference to the file to delete + var desertRef = storageRef.child('images/desert.jpg'); + + // Delete the file + desertRef.delete().then(() => { + // File deleted successfully + }).catch((error) => { + // Uh-oh, an error occurred! + }); + // [END storage_delete_file] +} diff --git a/storage/download-files.js b/storage/download-files.js new file mode 100644 index 00000000..cb2af375 --- /dev/null +++ b/storage/download-files.js @@ -0,0 +1,80 @@ +import firebase from "firebase/app"; +import "firebase/storage"; + +function downloadCreateRef() { + // [START storage_download_create_ref] + // Create a reference with an initial file path and name + var storage = firebase.storage(); + var pathReference = storage.ref('images/stars.jpg'); + + // Create a reference from a Google Cloud Storage URI + var gsReference = storage.refFromURL('gs://bucket/images/stars.jpg'); + + // Create a reference from an HTTPS URL + // Note that in the URL, characters are URL escaped! + var httpsReference = storage.refFromURL('https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg'); + // [END storage_download_create_ref] +} + +function downloadViaUrl() { + const storageRef = firebase.storage().ref(); + + // [START storage_download_via_url] + storageRef.child('images/stars.jpg').getDownloadURL() + .then((url) => { + // `url` is the download URL for 'images/stars.jpg' + + // This can be downloaded directly: + var xhr = new XMLHttpRequest(); + xhr.responseType = 'blob'; + xhr.onload = (event) => { + var blob = xhr.response; + }; + xhr.open('GET', url); + xhr.send(); + + // Or inserted into an element + var img = document.getElementById('myimg'); + img.setAttribute('src', url); + }) + .catch((error) => { + // Handle any errors + }); + // [END storage_download_via_url] +} + +function downloadFullExample() { + const storageRef = firebase.storage().ref(); + + // [START storage_download_full_example] + // Create a reference to the file we want to download + var starsRef = storageRef.child('images/stars.jpg'); + + // Get the download URL + starsRef.getDownloadURL() + .then((url) => { + // Insert url into an tag to "download" + }) + .catch((error) => { + // A full list of error codes is available at + // https://firebase.google.com/docs/storage/web/handle-errors + switch (error.code) { + case 'storage/object-not-found': + // File doesn't exist + break; + case 'storage/unauthorized': + // User doesn't have permission to access the object + break; + case 'storage/canceled': + // User canceled the upload + break; + + // ... + + case 'storage/unknown': + // Unknown error occurred, inspect the server response + break; + } + }); + // [END storage_download_full_example] +} diff --git a/storage/file-metadata.js b/storage/file-metadata.js new file mode 100644 index 00000000..cef42364 --- /dev/null +++ b/storage/file-metadata.js @@ -0,0 +1,75 @@ +import firebase from "firebase/app"; +import "firebase/storage"; + +function getMetadata() { + const storageRef = firebase.storage().ref(); + + // [START storage_get_metadata] + // Create a reference to the file whose metadata we want to retrieve + var forestRef = storageRef.child('images/forest.jpg'); + + // Get metadata properties + forestRef.getMetadata() + .then((metadata) => { + // Metadata now contains the metadata for 'images/forest.jpg' + }) + .catch((error) => { + // Uh-oh, an error occurred! + }); + // [END storage_get_metadata] +} + +function updateMetadata() { + const storageRef = firebase.storage().ref(); + + // [START storage_update_metadata] + // Create a reference to the file whose metadata we want to change + var forestRef = storageRef.child('images/forest.jpg'); + + // Create file metadata to update + var newMetadata = { + cacheControl: 'public,max-age=300', + contentType: 'image/jpeg' + }; + + // Update metadata properties + forestRef.updateMetadata(newMetadata) + .then((metadata) => { + // Updated metadata for 'images/forest.jpg' is returned in the Promise + }).catch((error) => { + // Uh-oh, an error occurred! + }); + // [END storage_update_metadata] +} + +function deleteMetadata() { + const storageRef = firebase.storage().ref(); + const forestRef = storageRef.child('images/forest.jpg'); + + // [START storage_delete_metadata] + + // Create file metadata with property to delete + var deleteMetadata = { + contentType: null + }; + + // Delete the metadata property + forestRef.updateMetadata(deleteMetadata) + .then((metadata) => { + // metadata.contentType should be null + }).catch((error) => { + // Uh-oh, an error occurred! + }); + // [END storage_delete_metadata] +} + +function customMetadata() { + // [START storage_custom_metadata] + var metadata = { + customMetadata: { + 'location': 'Yosemite, CA, USA', + 'activity': 'Hiking' + } + }; + // [END storage_custom_metadata] +} diff --git a/storage/index.js b/storage/index.js index 02598d88..7a7db0df 100644 --- a/storage/index.js +++ b/storage/index.js @@ -1,6 +1,44 @@ import firebase from "firebase/app"; import "firebase/storage"; +function initialize() { + // [START storage_initialize] + // Set the configuration for your app + // TODO: Replace with your app's config object + var firebaseConfig = { + apiKey: '', + authDomain: '', + databaseURL: '', + storageBucket: '' + }; + firebase.initializeApp(firebaseConfig); + + // Get a reference to the storage service, which is used to create references in your storage bucket + var storage = firebase.storage(); + // [END storage_initialize] +} + +function multipleBuckets() { + // [START storage_multiple_buckets] + // Get a non-default Storage bucket + var storage = firebase.app().storage("gs://my-custom-bucket"); + // [END storage_multiple_buckets] +} + +function storageCustomApp() { + const customApp = firebase.initializeApp({ + // ... custom stuff + }); + + // [START storage_custom_app] + // Get the default bucket from a custom firebase.app.App + var storage = customApp.storage(); + + // Get a non-default bucket from a custom firebase.app.App + var storage = customApp.storage("gs://my-custom-bucket"); + // [END storage_custom_app] +} + /** * @param {File} file */ diff --git a/storage/list-files.js b/storage/list-files.js new file mode 100644 index 00000000..ef248da7 --- /dev/null +++ b/storage/list-files.js @@ -0,0 +1,53 @@ +import firebase from "firebase/app"; +import "firebase/storage"; + +function listAll() { + const storageRef = firebase.storage().ref(); + + // [START storage_list_all] + // Create a reference under which you want to list + var listRef = storageRef.child('files/uid'); + + // Find all the prefixes and items. + listRef.listAll() + .then((res) => { + res.prefixes.forEach((folderRef) => { + // All the prefixes under listRef. + // You may call listAll() recursively on them. + }); + res.items.forEach((itemRef) => { + // All the items under listRef. + }); + }).catch((error) => { + // Uh-oh, an error occurred! + }); + // [END storage_list_all] +} + +function listPaginate() { + const storageRef = firebase.storage().ref(); + + // [START storage_list_paginate] + async function pageTokenExample(){ + // Create a reference under which you want to list + var listRef = storageRef.child('files/uid'); + + // Fetch the first page of 100. + var firstPage = await listRef.list({ maxResults: 100}); + + // Use the result. + // processItems(firstPage.items) + // processPrefixes(firstPage.prefixes) + + // Fetch the second page if there are more elements. + if (firstPage.nextPageToken) { + var secondPage = await listRef.list({ + maxResults: 100, + pageToken: firstPage.nextPageToken, + }); + // processItems(secondPage.items) + // processPrefixes(secondPage.prefixes) + } + } + // [END storage_list_paginate] +} diff --git a/storage/upload-files.js b/storage/upload-files.js new file mode 100644 index 00000000..988fc3eb --- /dev/null +++ b/storage/upload-files.js @@ -0,0 +1,212 @@ +import firebase from "firebase/app"; +import "firebase/storage"; + +function uploadRef() { + // [START storage_upload_ref] + // Create a root reference + var storageRef = firebase.storage().ref(); + + // Create a reference to 'mountains.jpg' + var mountainsRef = storageRef.child('mountains.jpg'); + + // Create a reference to 'images/mountains.jpg' + var mountainImagesRef = storageRef.child('images/mountains.jpg'); + + // While the file names are the same, the references point to different files + mountainsRef.name === mountainImagesRef.name; // true + mountainsRef.fullPath === mountainImagesRef.fullPath; // false + // [END storage_upload_ref] +} + +/** + * @param {File} file + */ +function uploadBlob(file) { + const ref = firebase.storage().ref().child('some-child'); + + // [START storage_upload_blob] + // 'file' comes from the Blob or File API + ref.put(file).then((snapshot) => { + console.log('Uploaded a blob or file!'); + }); + // [END storage_upload_blob] +} + +function uploadBytes() { + const ref = firebase.storage().ref().child('some-child'); + + // [START storage_upload_bytes] + var bytes = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21]); + ref.put(bytes).then((snapshot) => { + console.log('Uploaded an array!'); + }); + // [END storage_upload_bytes] +} + +function uploadString() { + const ref = firebase.storage().ref().child('some-child'); + + // [START storage_upload_string] + // Raw string is the default if no format is provided + var message = 'This is my message.'; + ref.putString(message).then((snapshot) => { + console.log('Uploaded a raw string!'); + }); + + // Base64 formatted string + var message = '5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB'; + ref.putString(message, 'base64').then((snapshot) => { + console.log('Uploaded a base64 string!'); + }); + + // Base64url formatted string + var message = '5b6p5Y-344GX44G-44GX44Gf77yB44GK44KB44Gn44Go44GG77yB'; + ref.putString(message, 'base64url').then((snapshot) => { + console.log('Uploaded a base64url string!'); + }); + + // Data URL string + var message = 'data:text/plain;base64,5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB'; + ref.putString(message, 'data_url').then((snapshot) => { + console.log('Uploaded a data_url string!'); + }); + // [END storage_upload_string] +} + +/** + * @param {File} file + */ +function uploadMetadata(file) { + const storageRef = firebase.storage().ref(); + + // [START storage_upload_metadata] + // Create file metadata including the content type + var metadata = { + contentType: 'image/jpeg', + }; + + // Upload the file and metadata + var uploadTask = storageRef.child('images/mountains.jpg').put(file, metadata); + // [END storage_upload_metadata] +} + +/** + * @param {File} file + */ +function manageUploads(file) { + const storageRef = firebase.storage().ref(); + + // [START storage_manage_uploads] + // Upload the file and metadata + var uploadTask = storageRef.child('images/mountains.jpg').put(file); + + // Pause the upload + uploadTask.pause(); + + // Resume the upload + uploadTask.resume(); + + // Cancel the upload + uploadTask.cancel(); + // [END storage_manage_uploads] +} + +/** + * @param {File} file + */ +function monitorUpload(file) { + const storageRef = firebase.storage().ref(); + + // [START storage_monitor_upload] + var uploadTask = storageRef.child('images/rivers.jpg').put(file); + + // Register three observers: + // 1. 'state_changed' observer, called any time the state changes + // 2. Error observer, called on failure + // 3. Completion observer, called on successful completion + uploadTask.on('state_changed', + (snapshot) => { + // Observe state change events such as progress, pause, and resume + // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded + var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; + console.log('Upload is ' + progress + '% done'); + switch (snapshot.state) { + case firebase.storage.TaskState.PAUSED: // or 'paused' + console.log('Upload is paused'); + break; + case firebase.storage.TaskState.RUNNING: // or 'running' + console.log('Upload is running'); + break; + } + }, + (error) => { + // Handle unsuccessful uploads + }, + () => { + // Handle successful uploads on complete + // For instance, get the download URL: https://firebasestorage.googleapis.com/... + uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => { + console.log('File available at', downloadURL); + }); + } + ); + // [END storage_monitor_upload] +} + +/** + * @param {File} file + */ +function uploadHandleError(file) { + const storageRef = firebase.storage().ref(); + + // [START storage_upload_handle_error] + // Create the file metadata + var metadata = { + contentType: 'image/jpeg' + }; + + // Upload file and metadata to the object 'images/mountains.jpg' + var uploadTask = storageRef.child('images/' + file.name).put(file, metadata); + + // Listen for state changes, errors, and completion of the upload. + uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed' + (snapshot) => { + // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded + var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; + console.log('Upload is ' + progress + '% done'); + switch (snapshot.state) { + case firebase.storage.TaskState.PAUSED: // or 'paused' + console.log('Upload is paused'); + break; + case firebase.storage.TaskState.RUNNING: // or 'running' + console.log('Upload is running'); + break; + } + }, + (error) => { + // A full list of error codes is available at + // https://firebase.google.com/docs/storage/web/handle-errors + switch (error.code) { + case 'storage/unauthorized': + // User doesn't have permission to access the object + break; + case 'storage/canceled': + // User canceled the upload + break; + + // ... + + case 'storage/unknown': + // Unknown error occurred, inspect error.serverResponse + break; + } + }, + () => { + // Upload completed successfully, now we can get the download URL + uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) { + console.log('File available at', downloadURL); + }); + } + ); + // [END storage_upload_handle_error] +}