因此,这就是我使用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数据库中的两个不同位置。
单个云函数中的返回语句不能超过1个。
因此,有什么方法可以使用单个功能将两个信息数据添加到Firebase数据库中它们各自的唯一位置中?我的意思是包含第二个函数的return语句可以在第一个函数本身中执行吗?这将极大地帮助减小代码的大小,并在一定程度上有助于节省函数调用。
如果要在单个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);
})