所以这就是我在firebase实时数据库中使用firebase云函数添加子节点并为其赋值的方式。
export const addUserInfo = functions.database
.ref('/Users/{UserID}')
.onCreate((snapshot, context) => {
const userData = snapshot.val()
const username = userData.username
const userUID = context.params.UserID
console.log(`${username} has UID ${userUID}.`)
return snapshot.ref.parent!.parent!.child('userInfo').child(`${userUID}`).set({ "username": newUsername, "uid": userUID})
})
我还有另一个类似的功能:
export const addUserToWhitelist = functions.database
.ref('/Users/{UserID}')
.onCreate((snapshot, context) => {
const userData = snapshot.val()
const username = userData.username
console.log(`${username} has been whitelisted`)
return snapshot.ref.parent!.parent!.child('whitelist').set({ "username": newUsername})
})
所以基本上,我使用两个独特的函数将用户信息添加到Firebase数据库中的两个不同位置。
在一个云函数中不能有多个return语句
那么,我有没有办法用一个函数将这两个信息数据添加到firebase数据库中各自独特的位置?我的意思是,包含第二个函数的返回语句可以在第一个函数中执行吗?这将大大有助于减少代码的大小,并在一定程度上有助于保存函数调用。
如果要将数据写入单个Cloud Function中的两个位置,可以使用Promise.all
等待两个写入都完成。
类似于:
export const addUserToWhitelist = functions.database
.ref('/Users/{UserID}')
.onCreate((snapshot, context) => {
const userData = snapshot.val()
const username = userData.username
console.log(`${username} has been whitelisted`)
const parent = snapshot.ref.parent!.parent!
return Promise.all([
parent.child('userInfo').child(userUID).set({ "username": newUsername, "uid": userUID}),
parent.child('whitelist').set({ "username": newUsername})
]);
})
或者,您可以在对数据库的单个写入操作中执行这两个更新,方法是将它们封装到单个多位置更新中:
export const addUserToWhitelist = functions.database
.ref('/Users/{UserID}')
.onCreate((snapshot, context) => {
const userData = snapshot.val()
const username = userData.username
console.log(`${username} has been whitelisted`)
let updates = {};
updates[`userInfo/${userUID}`] = { "username": newUsername, "uid": userUID};
updates['whitelist'] = { "username": newUsername};
return snapshot.ref.parent!.parent!.update(updates);
})