This sample demonstrates how to sync new data written to a Firebase database to a Google Sheet. It includes a method for obtaining, storing, and using Oauth2 tokens for Google API access.
This code is also described in this blog post.
See file functions/index.js for the Google Sheet sync code.
Use the HTTPS function authGoogleAPI to request Oauth2 tokens for the Google API.
The trigger function is appendRecordToSpreadsheet.
To test it out, use the HTTPS function testSheetWrite.
The function triggers on when data is added to the DATA_PATH of the active Firebase database. In this sample, objects written to DATA_PATH/{ID} in the form {firstColumn: value, secondColumn: value, thirdColumn: value} are appended to the sheet.
To deploy and test the sample:
- Create a Firebase project on the Firebase Console and visit the Storage tab.
- Clone this repo:
git clone https://github.com/firebase/functions-samples. - Open this sample's directory:
cd functions-samples/google-sheet-sync - Setup your project by running
firebase use --addand select the project you had created. - Install dependencies in the functions directory:
cd functions; npm install; cd - - Using the Google APIs Console create an OAuth Client ID Click this link, select your project and then choose Web Application. In Authorized redirect URIs, you’ll need to enter
https://{YOUR-PROJECT-ID}.firebaseapp.com/oauthcallback. - Configure your Google API client ID and secret by running:
firebase functions:config:set googleapi.client_id="YOUR_CLIENT_ID" googleapi.client_secret="YOUR_CLIENT_SECRET"
- Create a new Google Sheet, and copy the long string in the middle of the Sheet URL. This is the Spreadsheet ID.
- Configure your Google Spreadsheet ID by running:
firebase functions:config:set googleapi.sheet_id="YOUR_SPREADSHEET_ID" - Specify the path of the data in the Realtime Database that you want automatically copied to your Spreadsheet:
firebase functions:config:set watchedpaths.data_path="THE_DATA_PATH_YOU_WANT" - Deploy your project using
firebase deploy - Configure the app once by opening the following URL and going through the auth flow
https://{YOUR-PROJET-ID}.firebaseapp.com/authgoogleapi - To test, go to
{YOUR_PROJET_ID}.firebaseapp.com/testsheetwrite. This will automatically add some test data in your Firebase Realtime Database in the data path that you set inwatchedpaths.data_path. - Check your Google Sheet, to see these same values which have been appended via the trigger function.