gpt4 book ai didi

javascript - 在 firebase 云函数中拆分 index.js 文件时出错

转载 作者:行者123 更新时间:2023-12-02 23:30:20 24 4
gpt4 key购买 nike

我尝试将 index.js 文件拆分为多个文件。我想计算数据库引用中的 child 数量。以前我的 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);
});

但是我在部署时遇到in 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) => { ... }
}

关于javascript - 在 firebase 云函数中拆分 index.js 文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56535741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com