GithubHelp home page GithubHelp logo

firebase / snippets-web Goto Github PK

View Code? Open in Web Editor NEW
728.0 94.0 241.0 1.11 MB

Web snippets for firebase.google.com

License: Apache License 2.0

HTML 0.12% JavaScript 98.49% Shell 0.05% TypeScript 1.34%

snippets-web's Introduction

Firebase Web Snippets

This repository holds code snippets used in Web documentation on firebase.google.com.

These snippets are part of our documentation and best read in the context of a documentation page rather than used directly. If you're looking to get started with the Firebase Web SDK the best place to start is quickstart-js.

Example

Consider this page: https://firebase.google.com/docs/database/web/lists-of-data

Each snippet in the page is dynamically included from the source in this repository, in this case mostly from this file: https://github.com/firebase/snippets-web/blob/master/database/lists-of-data.js

Each snippet has a "region tag" which is defined by // [START tag] and // [END tag] comments. The code between the tags can be included in our documentation. Keeping the code on GitHub, rather than hard-coded into the HTML of our documentation, allows us to ensure the code is correct and up to date.

Contributing

We love contributions! See CONTRIBUTING.md for guidelines.

Build Status

Actions Status

snippets-web's People

Contributors

abeisgoat avatar chronologos avatar devkiloton avatar dpebot avatar dwyfrequency avatar egilmorez avatar grant avatar gregfenton avatar jamesdaniels avatar jhuleatt avatar jlara310 avatar jonasdev avatar kbsanders avatar kevinthecheung avatar klutchdev avatar kroikie avatar markarndt avatar morganchen12 avatar nestiank avatar nhienlam avatar nicolasgarnier avatar ochui avatar puf avatar rachelsaunders avatar sam-gc avatar samtstern avatar shabbirjodhpur avatar thatfiredev avatar torbet avatar vitaliytv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

snippets-web's Issues

Unused function parameter in distributed counter example

function incrementCounter(db, ref, num_shards) {
// Select a shard of the counter at random
const shard_id = Math.floor(Math.random() * num_shards).toString();
const shard_ref = ref.collection('shards').doc(shard_id);
// Update count
return shard_ref.update("count", firebase.firestore.FieldValue.increment(1));
}

The parameter db is unused in this code example. For the same example in other languages, they do not have this parameter, so it is unneeded here.

CollectionGroup error when i run in TypeScript

I thought i can run my typeScript with the JavaScript code snippet since i am able to for most of the code sample. But i hit a serious roadblock for CollectionGroup sample.

Below is my code

getCollectionGroup() {
    
    var museums = this.db.collectionGroup('landmarks').where('type', '==', 'museum');
    
    museums.get().then(function (querySnapshot) {
        querySnapshot.forEach(function (doc) {
            console.log(doc.id, ' => ', doc.data());
        });
});

And i get error

Property 'where' does not exist on type 'AngularFirestoreCollectionGroup'.

Where does `googleUser` come from?

providerData[i].uid === googleUser.getBasicProfile().getId()) {

I know that firebaseUser comes from this ( result.user):

signInWithPopup(auth, provider)
      .then((result) => {
        // This gives you a Google Access Token. You can use it to access the Google API.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token: string | undefined = credential?.accessToken;
        // The signed-in user info.
        const user = result.user;
.....

But where does googleUser come from?

> )]}'

)]}'
{
"id": "1fabcab4a6f89d9143c5483a0a07b9090da8c0dc",
"repo": "cihaz/genel/opengl-taลŸฤฑma",
"revizyon": "baลŸvurular/etiketler/android-s-v2-beta-3",
"yol": "ana bilgisayar/Android.bp"
}

$

Originally posted by @caniso in caniso/codeql-uboot#3 (comment)

can you teach me how to run these programs

do I just type node .js?

cause when I did it gave me an error

node firebase.js
/home/bb/firebase.js:1
(function (exports, require, module, __filename, __dirname) { import firebase from "firebase/app";
^^^^^^^^

SyntaxError: Unexpected identifier
at new Script (vm.js:73:7)

How to prompt user for credentials?

manage.js has

const user = firebase.auth().currentUser;

// TODO(you): prompt the user to re-provide their sign-in credentials
const credential = promptForCredentials();

user.reauthenticateWithCredential(credential).then(() => {
  // User re-authenticated.
}).catch((error) => {
  // An error ocurred
  // ...
});

But what does it mean by prompt the user to re-provide credentials? Does it mean their email and password or...?

No example for collectionGroup for Firestore V9 (modular) in the documentation

I'm upgrading a Firebase app to version 9, and I can't find in the documentation how collectionGroup is used.

This is an example from the current documentation

collectionGroup-example
And here is the corresponding code snippet:

var museums = db.collectionGroup('landmarks').where('type', '==', 'museum');
museums.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.id, ' => ', doc.data());
});
});


From the code snippets here on GitHub it seems like it has been already implemented, yet it doesn't appear in the documentation.

import { collectionGroup, query, where, getDocs } from "firebase/firestore";
const museums = query(collectionGroup(db, 'landmarks'), where('type', '==', 'museum'));
const querySnapshot = await getDocs(museums);
querySnapshot.forEach((doc) => {
console.log(doc.id, ' => ', doc.data());
});

TypeError: querySnapshot.forEach is not a function

TypeError: querySnapshot.forEach is not a function

import { collection, getDocs } from "firebase/firestore"; 

const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
  console.log(`${doc.id} => ${doc.data()}`);
});

here it says

TypeError: querySnapshot.forEach is not a function

Improve accuracy of account linking snippets for Auth

This (old) email thread explains some of the shortcomings with our snippets on this page:
https://groups.google.com/d/msgid/firebase-talk/86666e16-7489-43fd-a357-96b39d56d546%40googlegroups.com?utm_medium=email&utm_source=footer

The file in question is:
https://github.com/firebase/snippets-web/blob/cee9068490fbfb03c123fbda87bc08a73a122520/auth/link-multiple-accounts.js

To quote the thread:

line 128 I believe should be:

repo.delete(prevUserData);

line 153 I don't think is needed or works as it's out of scope

line 140 & the chained logic I'm unsure of. I'm approaching differently since I'm only going from anonymous to permanent & I don't need the anonymous account anymore at this point so I delete it & merge data into the signed in account.

I know you're keeping it brief but I think this could fail if the linked account is already linked so might at least want a note about it ๐Ÿคทโ€โ™‚๏ธ Also I haven't tried in this context, but once you've linked the credential can't you just merge w/out signing in again?

Population Spelling Mistake

There is a spelling mistake (popuation while it would be population) at line 14

import { collection, doc, getDoc, query, orderBy, startAt } from "firebase/firestore";
const citiesRef = collection(db, "cities");
const docSnap = await getDoc(doc(citiesRef, "SF"));
// Get all cities with a population bigger than San Francisco
const biggerThanSf = query(citiesRef, orderBy("popuation"), startAt(docSnap));
// ...

How to use modular SDK over CDN?

It looks the documentation now shows importing the Firebase SDK v9 over CDN now.

However the code snippets there show usage with import (I doubt if the snippets are just getting copied from the 'with NPM' tab).

import firebase from "firebase/compat/app";

const firebaseApp = firebase.initializeApp({ /* config */ });

I do see it uses /compat (also in the script URLs) which means it uses the v8 syntax.

I just wanted to confirm if the modular syntax is available for use over CDN on simple HTML JS web apps (not using any framework) as in this question.

Custom Object converter getting: Error getting document: TypeError: snapshot is not a function

class City {
constructor (name, state, country ) {
this.name = name;
this.state = state;
this.country = country;
}
toString() {
return this.name + ', ' + this.state + ', ' + this.country;
}
}
// Firestore data converter
cityConverter = {
toFirestore: function(city) {
return {
name: city.name,
state: city.state,
country: city.country
}
},
fromFirestore: function(snapshot, options){
const data = snapshot.data(options);
return new City(data.name, data.state, data.country)
}
}

When trying to call read custom object, I'm getting snapshot.data is not a function error

Error getting document: TypeError: snapshot is not a function

i have an issue using linkWithCredential(user , AuthCredential)

Firebase Auth JS V9

Description :

in this line of snippet code the documentation shows calling linkWithCredential(user , OAuthCredential) instead of linkWithCredential(user , AuthCredential)
the incompatibility between AuthCredential and OAuthCredential produce an error of
credential._linkToIdToken is not a function . i could'nt find any solution to link and account when 'auth/account-exists-with-different-credential' produced . since it's not clear how to handle this case in V9 without produces the previous Error

return linkWithCredential(prevUser, credential)

Error on firebase require in node JS

I'm trying to use firebase auth in the backend for authentification i tried to follow the firebase documentation to import these functions which does not work for nodeJS

import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
const auth = getAuth();
createUserWithEmailAndPassword(auth, email, password)
  .then((userCredential) => {
    Signed in 
    const user = userCredential.user;
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;  });

i tried to change the into a const ... = require() instead of an import
but now i'm getting this error
FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).

if i use the old version with firebase 8 requiring firebase i'm getting this error,
[Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" - Firebase](https://stackoverflow.com/questions/69200493/error-err-package-path-not-exported-no-exports-firebase)

i'm trying to create a user in a express app endpoint:

   app.post('/signup', (req, res) => {
    const newUser = {
        email: req.body.email,
        password: req.body.password,
        confirmPassword: req.body.confirmPassword,
        handle: req.body.handle,
    }

    createUserWithEmailAndPassword(auth, newUser.email, newUser.password)
        .then(data => {
            return res.status(201).json({ message: `user${data.user.uid} signed up succesfully` })
        })
        .catch(err => {
            console.error(err)
            return res.status(500).json({ error: err.code })
        })
   })

How can i solve my problem ??

ุจูˆุฑุง 35432

firebase.auth().signInWithEmailAndPassword(email, password)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
// ...
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
});

How to use Google Access Token to call Google Drive API

Iโ€™m using Firebase Authentication mechanism and the scope I have provided https://www.googleapis.com/auth/drive

While running application, it asked for user login along with user's consent for Google drive access. After successful authentication it returns a Firebase Id Token.

In the next step application requires to access user's Google Drive. As I know Google Drive API requires OAuth Access token while application has Firebase Token.

https://www.googleapis.com/drive/v3/files

My questions is: How to generate OAuth Access token which is capable to access user's Google drive? OR Is there any alternate solution for this?

File upload to firebase via web fails for files with larger file-size

The code mentioned in the below link uploads a file to firebase storage:
https://github.com/firebase/snippets-web/blob/4b496235d2db433354ebb8084d59eba1263769a6/storage/upload-files.js
This works fine for smaller sized files. But fails when we try to upload files greater than 80MB. Th allowed limit is 5TB. So the file size is within the allowed range. When I try to upload a larger sized file, it uploads successfully till 99% with all the preflight requests being successful. But when the last chunk gets uploaded , the request fails with CORS error even though all the required permissions are granted and the same code works fine for smaller file sizes. Also, the last preflight request is also successful. So, how to resolve this issue?

FirebaseError

import { collection, doc, setDoc } from "firebase/firestore";
const citiesRef = collection(db, 'cities');
await Promise.all([
setDoc(doc(citiesRef, 'SF', 'landmarks'), {
name: 'Golden Gate Bridge',
type: 'bridge'
}),
setDoc(doc(citiesRef, 'SF', 'landmarks'), {
name: 'Legion of Honor',
type: 'museum'
}),
setDoc(doc(citiesRef, 'LA', 'landmarks'), {
name: 'Griffith Park',
type: 'park'
}),
setDoc(doc(citiesRef, 'LA', 'landmarks'), {
name: 'The Getty',
type: 'museum'
}),
setDoc(doc(citiesRef, 'DC', 'landmarks'), {
name: 'Lincoln Memorial',
type: 'memorial'
}),
setDoc(doc(citiesRef, 'DC', 'landmarks'), {
name: 'National Air and Space Museum',
type: 'museum'
}),
setDoc(doc(citiesRef, 'TOK', 'landmarks'), {
name: 'Ueno Park',
type: 'park'
}),
setDoc(doc(citiesRef, 'TOK', 'landmarks'), {
name: 'National Museum of Nature and Science',
type: 'museum'
}),
setDoc(doc(citiesRef, 'BJ', 'landmarks'), {
name: 'Jingshan Park',
type: 'park'
}),
setDoc(doc(citiesRef, 'BJ', 'landmarks'), {
name: 'Beijing Ancient Observatory',
type: 'museum'
})
]);

Invalid document reference. Document references must have an even number of segments, but cities/SF/landmarks has 3.

Misleading/incorrect example for firestore querying

Example from https://firebase.google.com/docs/firestore/query-data/queries#web-v8_4 is incorrect or misleading.

citiesRef.where("state", "==", "CA");
citiesRef.where("population", "<", 100000);
citiesRef.where("name", ">=", "San Francisco");

This example shows that you can chain query methods but it is incorrect. Query class is immutable, correct example will be

let citiesRef = firestore.collection('cities');

citiesRef = citiesRef.where("state", "==", "CA");
citiesRef = citiesRef.where("population", "<", 100000);
citiesRef = citiesRef.where("name", ">=", "San Francisco");

Please check this main issue googleapis/nodejs-firestore#483

Add a simple linter for snippets

Should check basic things like:

  • Consistent use of " vs '
  • Consistent use of (parens) => for single-argument arrow functions

Should not attempt to adjust indentation or line breaks anywhere, snippets often need to break those conventions.

how to link to phone Auth?

I see you show how to create login and link to other Auth providers, but how do we link a phone Auth method to an existing user?

Add More Info to Readme

Hello, I cannot find information explaining how to utilize this repo neither in the readme nor in the snippets.md.

I believe this repository would benefit from some elaboration. I wanted to offer a PR myself, but I can't even figure out how to implement this, or if this hosts to a VSC extension.

Thank you either way, I have added this potent repo to my watch list. ๐Ÿ™‡๐Ÿผโ€โ™‚๏ธ

How do you limit documents when using getDocs?

im trying to limit the documents i get, I am using ,limit after collection in the getdocs function. It's not working. Please tell me the right way
const querySnapshot = await getDocs(
collection(db, collectionName.Name),
limit(20)
);

where does "db" come from?

Almost all the docs do this, I have no idea where "db" came from. I'm also not sure if I should be using web9 or nodejs, but it's often a lot of samples are missing one or both, or are less clearly labeled.

import { runTransaction } from "firebase/firestore";
try {
await runTransaction(db, async (transaction) => {
const sfDoc = await transaction.get(sfDocRef);
if (!sfDoc.exists()) {
throw "Document does not exist!";
}
const newPopulation = sfDoc.data().population + 1;
transaction.update(sfDocRef, { population: newPopulation });
});
console.log("Transaction successfully committed!");
} catch (e) {
console.log("Transaction failed: ", e);
}

How do i add a field of type 'reference' or 'geopoint' to a doc? This example is missing from the documentation

var docData = {
stringExample: "Hello world!",
booleanExample: true,
numberExample: 3.14159265,
dateExample: firebase.firestore.Timestamp.fromDate(new Date("December 10, 1815")),
arrayExample: [5, true, "hello"],
nullExample: null,
objectExample: {
a: 5,
b: {
nested: "foo"
}
}
};
db.collection("data").doc("one").set(docData).then(() => {
console.log("Document successfully written!");
});

Snippet not correct, missing initializeApp()

Hi, this snippet:

import { getApp } from "firebase/app";
import { getFunctions, connectFunctionsEmulator } from "firebase/functions";
const functions = getFunctions(getApp());
connectFunctionsEmulator(functions, "localhost", 5001);
brings the error line 11:
No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).

is it normal? cause it is indeed fixed if the function is added it works

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.