Firebase
Firebase
- Copy your project settings under **Firebase SDK snippet** into your local project
(ie your project's `api key`, `auth domain`, `databaseURL`, etc)
- Create a file (firebase.js or config.js Any name that suits you is fine)
> The above line imports one of firebase SDKS which is use to initialize our
application. **Firebase app**(the core Firebase SDK) is always required and must be
listed first. You can now have access to each of firebase product through the
firebase namespace
> **Note** *The reason why we did not import everything from firebase ie **import
app from 'firebase'** is that, loading the entire SDK is not efficient for
production web apps*
- Initialize firebase.
```js
const app = firebase.initializeApp({
apiKey: process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_DATABASE_URL,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_ID
});
```
**Optionally**
> This command connects your local machine with firebase and gives your access to
your firebase projects
> This command links your local app directory with firebase, generates a
firebase.json file, and prompts you to specify a public root directory
# Firebase Authentication
## onAuthStateChange
```js
firebase.auth().onAuthStateChange(callback to return an observable)
```
```js
import {authState} from 'rxfire/auth';
authState(auth());
```
```js
await firebase.auth().createUserWithEmailAndPassword(email, password)
```
```js
await firebase.auth().signInWithEmailAndPassword(email, password)
```
**Google**
```js
const provider = new firebase.auth.GoogleAuthProvider()
```
**Facebook**
```js
const provider = new firebase.auth.FacebookAuthProvider()
```
**Twitter**
```js
const provider = new firebase.auth.TwitterAuthProvider()
```
**Github**
```js
const provider = new firebase.auth.GithubAuthProvider()
```
**Popup**
```js
await firebase.auth().signInWithPopup(provider)
```
**Redirect**
```js
await signInWithRedirect(provider);
```
## Sign Out
```js
await auth().signOut();
```
# Cloud Firestore
**To use firebase cloud firestore, first you'll need to import firestore from
firebase.**
```js
import firestore from 'firebase/firestore';
```
- Connect to a collection:
```js
firestore.collection('books'); // returns a collection reference called books
```
- Connect to a document:
```js
firestore.doc(`/books/id`); // returns a specific document refercence
```
## Resolving Promises
All or 95% of cloud firestore is asynchronous and also **promised based**
- To resolve a promise you can either use the then and catch approach or the async
and await approach.
- After successfully resolving the promise, a **snapshot** is returned. A snapshot
is basically data at that particular point in time based on your query.
- QuerySnapshot is what is returned next.
```js
firestore.collection('books').add(data); // returns a promise
// Alternatively
firestore.collection('books').set(data);
```
**Note: set also creates a new document if the documents being set does not exist
**
```js
import { collectionData } from 'rxfire/firestore';
```js
import {docData} from 'rxfire/firestore';
```
```js
firestore.doc(`/books/id`).update(data); // returns a promise
// Alternatively
firestore.collection('books').doc('id').update(data, {merge: true})
```
**Note: updating a document without {merge: true} overwrites the entire document.
But if {merge:true} is specified, prevents the entire document from being
overwritten**
# Cloud Functions
To setup cloud functions locally, you'll need **node pacakage manager(npm) and
firebase CLI**
`npm i -g firebase-tools`
Here, a couple of question will be asked. Are you ready to proceed(choose: yes[y]),
Select a project to link with, Language to use (javascript/typescript), Use
Eslint(y/n), Install dependencies(choose: yes[y])
3. A folder called **functions** with it's dependecies will be created. All cloud
function logic will be wriiten in a folder called index.js
# Storage
**not ready**
# Messaging
**not ready**
# Firebase Concepts
## Cloud Firestore:
### Collections
Collections don't store data on their own. Collections are containers that holds
multiple documents that can be queried.
### Documents
Data in a kind of json format. The rule of thumb here is that it is important to
make your collections large and your document small (1mb or smaller).
**The solution**
- **Denormalize** the data and save the collection as a **root collection**.
- After creating the root collection, you will need to save the user id of the
associated user on each individual document.
- With this, we can reference multiple user Ids to create a many-to-many
relationship.
// or
firestore.doc('/path to the document')
```
# Ordering
Cloud firestore supports some SQLite-like queries
<hr>
# Firebase CLI
You can use firebase command line interface to create a complete firebase project
just like you do using the graphical user interface in your firebase console
dashboard.To use firebase cli, you must first of all install **firebase-tools**
```javascript
npm i -g firebase-tools
```
After you're done installing firebase-tools, log into firebase by running the
command ```javascript firebase login```
**Note:** In case you're adding multiple development environment, run the following
commands:
- Select a second project to add by running the command:
```javascript
firebase use --add
```
- Choose a project from the list
- Give the selected project an **alias** let's say *production*
- Switch to the development project by running the command:
```javascript
firebase use default
```
**Recommended Approach:**
Implicit initialization works by loading Firebase javascript from a special /__/
folder. When we deploy our app to Firebase this route will exist for us but locally
we will need to do a little more work to set it up.
In your favorite code editor open up the build/index.html that was created by
firebase init. At the top of the body tag you will see a series of Firebase related
script tags, copy it.
Paste them in your public/index.html file at the top of the body tag. Feel free to
remove features you are not using.
To authenticate your application with a provider like google, follow the steps
below:
Moreover, using **onAuthStaeChange**, we can track the current user. This will fire
or get called when a user is either loggedin or logged out. When that happens we
either get a user object or null.
# Custom Claims
## Cloud functions
Cloud functions allow us to run functions on the server and it is good for code you
don't want to expose on the client and perform tasks that are not available to
client users.
## Inside index.js
This should be your setup:
```javascript
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.api = functions.https.onRequest(app);
```