简体   繁体   中英

Synce Firestore data to google sheets

I am trying to sync data from my Firestore to my google sheets.

I have created a serviceAccount and saved the credentials in JSON file

The functions folder succesfully deploys however the function is executing with errors.

Below is my index.js

var functions = require('firebase-functions')
var admin = require('firebase-admin')
var { google } = require('googleapis')
var sheets = google.sheets('v4')
admin.initializeApp()

var spreadsheetId = '...'
var serviceAccount = require('./serviceAccount.json')

var jwtClient = new google.auth.JWT({
  email: serviceAccount.client_email,
  keys: serviceAccount.private_key,
  scopes: ['https://www.googleapis.com/auth/spreadsheets'],
})

var jwtAuthPromise = jwtClient.authorize()

exports.testFunction = functions.firestore.document('/scores/{docID}').onCreate(async snap => {
  if (snap.exists) {
    var obj = JSON.parse(JSON.stringify(snap.data()))
    await jwtAuthPromise
    sheets.spreadsheets.values.append(
      {
        auth: jwtClient,
        spreadsheetId: spreadsheetId,
        range: 'new!A2',
        valueInputOption: 'RAW',
        requestBody: {
          values: [[obj['Player'], obj['Score']]],
        },
      },
      (err, result) => {
        if (err) {
          // Handle error
          console.log(err)
        } else {
          console.log('%d cells updated.', result.updatedCells)
        }
      },
    )
  }
})

The cloud function triggers when any document is added to my scores collection, the data is then added to my google sheet.

When I manaually update my Firestore, these are the errors in my error log

testFunction Function execution took 2620 ms, finished with status: 'error'
testFunction Error: function crashed out of request scope Function invocation was interrupted.
testFunction
Error: No key or keyFile set. at GoogleToken.<anonymous> (/srv/node_modules/googleapis/node_modules/gtoken/build/src/index.js:115:23) at Generator.next (<anonymous>) at /srv/node_modules/googleapis/node_modules/gtoken/build/src/index.js:13:71 at new Promise (<anonymous>) at __awaiter (/srv/node_modules/googleapis/node_modules/gtoken/build/src/index.js:9:12) at GoogleToken.getTokenAsync (/srv/node_modules/googleapis/node_modules/gtoken/build/src/index.js:110:16) at GoogleToken.getToken (/srv/node_modules/googleapis/node_modules/gtoken/build/src/index.js:64:21) at JWT.<anonymous> (/srv/node_modules/googleapis/node_modules/google-auth-library/build/src/auth/jwtclient.js:144:40) at Generator.next (<anonymous>) at /srv/node_modules/googleapis/node_modules/google-auth-library/build/src/auth/jwtclient.js:22:71
testFunction
Error: No key or keyFile set.
    at GoogleToken.<anonymous> (/srv/node_modules/googleapis/node_modules/gtoken/build/src/index.js:115:23)
    at Generator.next (<anonymous>)
    at /srv/node_modules/googleapis/node_modules/gtoken/build/src/index.js:13:71
    at new Promise (<anonymous>)
    at __awaiter (/srv/node_modules/googleapis/node_modules/gtoken/build/src/index.js:9:12)
    at GoogleToken.getTokenAsync (/srv/node_modules/googleapis/node_modules/gtoken/build/src/index.js:110:16)
    at GoogleToken.getToken (/srv/node_modules/googleapis/node_modules/gtoken/build/src/index.js:64:21)
    at JWT.<anonymous> (/srv/node_modules/googleapis/node_modules/google-auth-library/build/src/auth/jwtclient.js:144:40)
    at Generator.next (<anonymous>)
    at /srv/node_modules/googleapis/node_modules/google-auth-library/build/src/auth/jwtclient.js:22:71
testFunction Unhandled rejection
testFunction
Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
testFunction
Function execution started

I've gotten Functions to integrate with Google Sheets by creating a promise that uses the Json file and returns the authorization when I need it. This is a trimmed version of the method I used but you can adapt it to your needs:

// Helper to get authorization
// (You may need to add the Drive scope 
// if you want to add additional users permission to edit the file)
var clientPromise = new Promise((resolve, reject) => {
    const client = new google.auth.JWT({
            keyFile: 'my_key_file.json',
            scopes: ['https://www.googleapis.com/auth/spreadsheets', 
                    'https://www.googleapis.com/auth/drive'],
        });

        resolve(client);
});

exports.myFunction = functions.firestore
.document('myCollection/{addedDoc}')
.onCreate((snap, context) => {
    // do something with the new document
    // ...
    return new Promise((resolve, reject) => {
        // You may not need this part but you can use a new promise here if you need it.
        console.log(snap);
        resolve(true);

    }).then(result => {
        return clientPromise;

    }).then(auth => {
        sheets = google.sheets({
            version: 'v4',
            auth: auth,
        });

        // do something with the sheets variable
        // ...
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM