在Firebase Cloud函数中拆分index.js文件时出错

时间:2019-06-11 02:37:56

标签: javascript node.js firebase google-cloud-functions

我尝试将 index.js 文件拆分为多个文件。我想计算数据库参考中的子代数。以前,我的 index.js 文件是

exports.updateUserBookCount = functions.database.ref('/Users/{userID}/Books/{bookID}')
      .onWrite(async (change,context)=>{

        const collectionRef = change.after.ref.parent;
        const userID = context.params.userID;
        const countRef = admin.database().ref(`/UserInfo/${userID}/usersBooks`);
        console.log("book counter : "+collectionRef);

        const bookList = await collectionRef.once('value');
        return await countRef.set(bookList.numChildren());

      });

我创建了新文件 counter.js ,它是


//counter.js
exports.userBookCount = function(change,context,admin){
    const collectionRef = change.after.ref.parent;
    const userID = context.params.userID;
    const countRef = admin.database().ref(`/UserInfo/${userID}/usersBooks`);
    console.log("book counter : "+collectionRef);

    const bookList = await collectionRef.once('value');
    return await countRef.set(bookList.numChildren());
}

然后我像

那样更改了 index.js

//index.js
const admin = require('firebase-admin');
admin.initializeApp();
const counter = require('./counter');
exports.updateUserBookCount = functions.database.ref('/Users/{userID}/Books/{bookID}')
      .onWrite(async (change,context)=>{
         counter.userBookCount(change,context,admin);
      });

但是我在counter.js 9:28中遇到错误错误。解析错误:部署时出现意外的令牌收集参考

1 个答案:

答案 0 :(得分:1)

我不清楚您的结构,但我猜您只是希望能够拆分文件以进行代码组织?如果是这样,这就是我的结构方式:

//index.js
const admin = require('firebase-admin')
const functions = require('firebase-functions')
admin.initializeApp()

const counter = require('./counter.js')

exports.updateUserBookCount = functions.database.ref('/Users/{userID}/Books/{bookID}').onWrite(counter);
//counter.js
const admin = require('firebase-admin')

//This function becomes counter in your index.js - you don't get counter.userBookCount because you have a single export from this file
module.exports = (change, context) => {
  // rest of your logic
}

//If you really want counter.userBookCount because you'll have other functions here, export multiple functions like this:
module.exports = {
  userBookCount: (change, context) => {
    // rest of your logic
  },
  someOtherBookFunction: (change, context) => { ... }
}