How to sync Firebase Database with Google Sheets? - firebase

I am working in an Ionic 3 project with ts to integrate Firebase into my app.
The below code I used to integrate firebase with Ionic project
constructor(angFire: AngularFireDatabase){
}
books: FirebaseListObservable<any>;
To send the data from my app to firebase, I used push method and to update entries I used update($key). Now I have all the data's in Firebase backend.
Now, how can I sync the firebase Database with Google Sheets so that each and every entry added to firebase backend has to get updated into sheets. I used a third party ZAPIER for this integration, but it would be nice if I get to learn on how to do this sync on my own.
Upon surfing, there are many tutorials to get the data's from the google sheets into Firebase. But I didn't come across any tutorials for vice versa.
I followed the below tutorial but it doesn't point to spreadsheets.
https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/firebase
Any help would be greatly appreciated!

I looked into importing Firebase right into Google Scripts either through the JavaScript SDK or or the REST API. Both have requirements/steps that Google Scripts cannot satisfy or that are extremely difficult to satisfy.
There is no foreseeable method of downloading the JavaScript SDK inside a Google Script because almost every method requires a DOM, which you don't have with a Google Sheet.
The REST API requires GoogleCredentials which, at a short glance, appear very difficult to get inside Google Scripts as well
So, the other option is to interact with Firebase in a true server side environment. This would be a lot of code, but here are the steps that I would take:
1) Setup a Pyrebase project so you can interact with your Firebase project via Python.
import pyrebase
config = {
"apiKey": "apiKey",
"authDomain": "projectId.firebaseapp.com",
"databaseURL": "https://databaseName.firebaseio.com",
"storageBucket": "projectId.appspot.com",
"serviceAccount": "path/to/serviceAccountCredentials.json"
}
firebase = pyrebase.initialize_app(config)
...
db = firebase.database()
all_users = db.child("users").get()
2) Setup a Google Scripts/Sheets project as a class that can interact with your Google Sheet
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'
class GoogleSheets:
...
# The rest of the functions from that link can go here
...
def write(self, sheet, sheet_name, row, col):
"""
Write data to specified google sheet
"""
if sheet == None or sheet == "":
print("Sheet not specified.")
return
day = time.strftime("%m/%d/%Y")
clock = time.strftime("%H:%M:%S")
datetime = day + " - " + clock
values = [[datetime]]
spreadsheetId = sheet
rangeName = sheet_name + "!" + str(row) + ":" + str(col)
body = {
'values': values
}
credentials = self.get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)
result = service.spreadsheets().values().update(
spreadsheetId=spreadsheetId, range=rangeName,
valueInputOption="RAW", body=body).execute()
3) Call the Google Sheets somewhere inside your Pyrebase project
from GoogleSheets import GoogleSheets
...
g = GoogleSheets()
g.write(<project-id>, <sheet-name>, <row>, <col>)
...
4) Set up a cron job to run the python script every so often
# every 2 minutes
*/2 * * * * /root/my_projects/file_example.py
You will need some basic server (Heroku, Digital Ocean) to run this.
This is not extensive because there is a lot of code to be written, but you could get the basics done. Makes we want to make a package now.

You can go for Zapier which is a 3rd party service through which you can easily integrate your Firebase and Google spreadsheets and vice versa. It has also got some support for google docs and other features.
https://zapier.com/zapbook/firebase/google-sheets/

Firebase can't be used as a trigger in Zapier, only as an action, so you can't send data from it to Google Sheets.

Related

Can't get rid of message When deploying Firebase apps to production, it is advisable to only import the individual SDK components you intend to use

I'm trying to use Firebase in my web project, and I can't understand how it works. I do:
import app from "firebase/app"; //1
import firebase from 'firebase'; //2
console.log(app === firebase); //3
it outputs true.
If I use 2 string my code to get data from firebase works and I get message about not using proper SDK in production
If I use 1 string I get an error from:
app.initializeApp(firebaseConfig);
const db = app.firestore();
Uncaught TypeError:
firebase_app__WEBPACK_IMPORTED_MODULE_0___default.a.firestore is not a
function
Please help me to sort out how to fix this.
I've got it, webpack is in charge. It wraps imported modules, that's why they are equal. Though, don't know how to optimize my module loads using webpack and firebase simultaneously.

Firebase auth in webapp without the SDK

Im trying to implement authentication on my SPA, and it works fine.
The way im doing it is like in the docs:
import firebase from 'firebase/app';
import 'firebase/auth';
const config = {
// ...
};
const firebaseApp = firebase.initializeApp(config);
// and somewhere else in the code(with all the arguments and stuff)
firebase.auth().createUserWithEmailAndPassword();
firebase.auth().signInWithEmailAndPassword();
Now, my problem is that these imports add too much to the app. I honestly don't think that 180KB(minified, but not compressed) is acceptable for an SPA that aims to work on mobile.
Just for comparison, my whole app, Vuejs + Router + Vuex + other 3~ small libraries and the app logic weight 170KB(minified but not compressed).
So I wanted to know if there is another solution, or if im doing it wrong, or if there is an easy workaround. Ideally, I would be able to just make an HTTP request and get back a JWP.
Well, I contacted firebase to add this as a feature request, and they suggested me to use for now the REST API for auth. It requires a custom token, but it is a good solution.
The documentation for the REST API:
https://firebase.google.com/docs/reference/rest/auth/
As far as I know, the actual endpoints you hit for Firebase auth isn't publicly documented nor have I seen them around the Web. With that said, if you are set on reducing your bundle size, your best bet is to pick apart the SDK and figure out how and what you need to construct.
signInWithEmailAndPassword is defined here and as you can see, it just calls out to another private function and so on.

Cloud Functions Firebase - create directory in default bucket - typescript

I am trying to write a function that updates a node in database and then create a directory in the default storage bucket.
admin.database().ref('messages').push({ original: original })
.then(() => {
//looking for something like this
//functions.storage.object().mkdir('myFolder');
})
Function samples from firebase docs use const gcs = require('#google-cloud/storage')(); but i am having hard time importing this package using typescript.
importing it this way does not work. instead of having access to gcs.bucket(...) i have access to gcs.Bucket
import * as gcs from '#google-cloud/storage';
I am looking for ways to get this import working or other ways i can use in typescript.
thanks.
Google Cloud Storage does not have a concept of "folders" -- as a pure object store, you can store a file with any arbitrary key. Various UIs (including the Firebase console) look for slashes in the object names to provide a virtual structure, but no actual structure exists.
On the import issue -- as of version 5.2.0 of the Admin SDK, you can just do:
admin.storage().bucket()
to get a reference to the Cloud Storage bucket.

Can Firebase RemoteConfig be accessed from cloud functions

I'm using Firebase as a simple game-server and have some settings that are relevant for both client and backend and would like to keep them in RemoteConfig for consistency, but not sure if I can access it from my cloud functions in a simple way (I don't consider going through the REST interface a "simple" way)
As far as I can tell there is no mention of it in the docs, so I guess it's not possible, but does anyone know for sure?
firebaser here
There is a public REST API that allows you to read and set Firebase Remote Config conditions. This API requires that you have full administrative access to the Firebase project, so must only be used on a trusted environment (such as your development machine, a server you control or Cloud Functions).
There is no public API to get Firebase Remote Config settings from a client environment at the moment. Sorry I don't have better news.
This is probably only included in newer versions of firebase (8th or 9th and above if I'm not mistaken).
// We first need to import remoteConfig function.
import { remoteConfig } from firebase-admin
// Then in your cloud function we use it to fetch our remote config values.
const remoteConfigTemplate = await remoteConfig().getTemplate().catch(e => {
// Your error handling if fetching fails...
}
// Next it is just matter of extracting the values, which is kinda convoluted,
// let's say you want to extract `game_version` field from remote config:
const gameVersion = remoteConfigTemplate.parameters.game_version.defaultValue.value
So parameters are always followed by the name of the field that you defined in Firebase console's remote config, in this example game_version.
It's a mouthful (or typeful) but that's how you get it.
Also note that if value is stored as JSON string, you will need to parse it before usage, commonly: JSON.parse(gameVersion).
Similar process is outlined in Firebase docs.

Google Datastore API from Datalab

I am working with Google's Datalab service, on a Google managed Computer engine(default), and I would like to call my Google Datastore's API. The documentation points to using the from google.appengine.ext import db library.
But when I execute this in a datalab code block I get ImportError: No module named appengine.ext.
I realize that this likly means that the App Engine SDK is not installed on the Datalab compute engine, My quetion is how can I then access the My Datastore namespace from my Datalab notebook?
It seems that I was better off using the gcloud package. Seeing as I updated the gcloud package before they where able to update documentation this is an example of the code I used:
from gcloud import datastore
from gcloud.datastore.key import Key
from gcloud.datastore.entity import Entity
import datetime
client = datastore.Client('project_id','namespace')
key = client.key('kind_name')
entity = datastore.Entity(key=key)
entity['datetime'] = datetime.datetime.now()
entity['some_other_column'] = 1
query = datastore.Query(client,kind='kind_name')
for result in query.fetch():
print result

Resources