首页 > 解决方案 > 在 Firebase 云功能中拆分 index.js 文件时出错

问题描述

我试图将我的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 error Parsing error: Unexpected token collectionRef部署时遇到错误。

标签: javascriptnode.jsfirebasegoogle-cloud-functions

解决方案


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

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

推荐阅读