javascript - 在 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部署时遇到错误。
解决方案
我不清楚您的结构,但我猜您只是希望能够拆分文件以进行代码组织?如果是这样,这就是我的结构:
//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) => { ... }
}
推荐阅读
- ruby-on-rails - 使用 capistrano+nginx 在单个数字海洋水滴中部署多个 Rails 应用程序
- python - 如何使用 h5py 将数据写入复合数据?
- reactjs - 如何在 React 中显示 Bootswatch 模式?
- python-3.x - AWS NEXRAD 和 pyart grid_from_radars
- c# - AutoFixture - 添加自定义,以便使用对象 ID 创建所有字典键
- spring - 自定义 Spring Boot Actuator 健康检查的整体健康状况
- sql-server-2008 - 仅当表 B 中不存在特定值时才从表 A 中获取值
- typescript - 使用 polyfill 时的安全打字稿编译
- python - 根据一列中的值替换整个数据框中的空值
- firebase - Firebase 通过 id 获取孙子