【发布时间】:2019-07-28 04:42:35
【问题描述】:
我创建了一个有趣的小型消息传递应用程序,我试图在用户之间进行对话,我做了一个连接查询,因为我在 firebase 上对我的架构进行了非规范化。
这是我的架构:
{
"messages": {
"-LZtqlYn2WB_1E-u4gUk-LZtqlYn2WB_1E-u4gUo": {
"-LZv3-yzpZ88lCLkGyRT": {
"createdAt": 1551474102199,
"receiverId": "-LZtqlYn2WB_1E-u4gUo",
"senderId": "-LZtqlYn2WB_1E-u4gUk",
"text": "alls"
}
},
"-LZtqlYn2WB_1E-u4gUo-L_8ymxVU_bS8r9Rux4y": {
"-L_8z5l0mNgJodbdh07O": {
"createdAt": 1551724473404,
"receiverId": "-LZtqlYn2WB_1E-u4gUo",
"senderId": "-L_8ymxVU_bS8r9Rux4y",
"text": "asfasfsf"
}
}
},
"users": {
"-LZtqlYn2WB_1E-u4gUo": {
"conversations": {
"-L_8ymxVU_bS8r9Rux4y": {
"conversationId": "-LZtqlYn2WB_1E-u4gUo-L_8ymxVU_bS8r9Rux4y",
"unseenCount": 5
}
},
"createdAt": 1551453853939,
"image": "https://d35arkf8909z2a.cloudfront.net/new_user.png",
"name": "John"
},
"-L_8ymxVU_bS8r9Rux4y": {
"createdAt": 1551724392288,
"image": "https://d35arkf8909z2a.cloudfront.net/new_user.png",
"name": "Meryl"
}
}
}
- 消息有一个唯一的 id,它是两个用户的组合,like this,并且有消息对象的子对象。
- 用户拥有会话集合,会话密钥是其他用户 ID。
我在js端的查询:
export function fetchConversations(userId) {
return (dispatch) => {
dispatch(fetchingConversations());
const rootRef = firebase.database().ref();
const conversations = rootRef.child(`users/${userId}/conversations`);
return conversations
.once('value', (snap) => {
const promises = [];
snap.forEach((data) => {
const { conversationId } = data.val();
const userRef = rootRef.child(`users/${data.key}`);
const messagesRef = rootRef.child(`messages/${conversationId}`).limitToLast(1);
promises.push(userRef.once('value'));
promises.push(messagesRef.once('value'));
});
return Promise.all(promises);
})
.then((results) => {
// this gives me conversations
// but I want users and messages
console.log(results.val());
});
};
}
我的问题
- fetchConversations 正在返回对话而不是用户和消息。如何返回用户和消息?
【问题讨论】:
-
是的,
child_addedlistener 你不能使用 Promise。 -
那我应该用什么来代替 child_added?
-
抱歉,我不知道 Firebase。没有什么方法可以让你们都成为孩子吗?
-
我认为,我可以使用值侦听器,但我不知道如何通过内部查询返回承诺。
标签: javascript firebase firebase-realtime-database promise