簡體   English   中英

將 Firestore 數據同步到 Google 表格

[英]Synce Firestore data to google sheets

我正在嘗試將 Firestore 中的數據同步到我的 Google 表格。

我創建了一個 serviceAccount 並將憑據保存在 JSON 文件中

函數文件夾成功部署,但函數執行時出錯。

下面是我的 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)
        }
      },
    )
  }
})

當任何文檔添加到我的scores集合時,雲功能會觸發,然后將數據添加到我的谷歌表中。

當我手動更新我的 Firestore 時,這些是我的錯誤日志中的錯誤

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

我通過創建一個使用 Json 文件並在需要時返回授權的承諾,使 Functions 與 Google Sheets 集成。 這是我使用的方法的精簡版本,但您可以根據自己的需要進行調整:

// 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
        // ...
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM