简体   繁体   中英

Firebase + Cloud functions dynamic onCall

I'm working on an angular/firebase web app and I started creating cloud functions onCall.

My app is based on a chat room:

messages
    |__1
       |__ 0
           |__ author: "foo"
           |__ message: "hello world"
           |__ playerExcluded: "foo2"
       |__ 1
           |__ author: "foo2"
           |__ message: "hello world"
           |__ playerExcluded: "foo"

I want to list all messages where currentUser != playerExluded (the user can see all messages except messages where he is excluded), that's why I started looking for cloud function. I'm just trying some things first before doing that, but it's not working as I want.

Here is what I wrote:

Cloud function:

const getMessages = functions.https.onCall((data, context) => {
    console.log('data: ', data);
    return new Promise((resolve, reject) => {
        admin.database().ref('/messages').child(data).on('value', msg => {
            resolve(msg.val());
        });
    })
});

module.exports = { getMessages };

(I used Promise because it was returning nothing without it. I used .on and not .once because I need to get messages dynamically).

Angular part:

Service:

messages: Message[] = [];
messagesSubject = new Subject<Message[]>();

getMessages() {
    firebase.functions().httpsCallable("getMessages")("1").then(result => {
        console.log("result: ", result);
        this.messages = [result.data[0]]; // let's try with first message
        console.log(this.messages);
        this.emitMessages();
    }).catch(error => {
        console.log("error:", error);
    });
}
emitMessages() {
    this.messagesSubject.next(this.messages);
}

Component:

messages;
messagesSubscription: Subscription;

constructor(private messageService: MessageService) { }

ngOnInit() {
    this.messageService.getMessages();
    this.messagesSubscription = this.messageService.messagesSubject.subscribe((result) => {
        console.log(result);
        this.messages = result;

    });
}

All will load fine. But it'll not be dynamic, I'll need to refresh my page to see changes.

Did I do something wrong ? Is firebase queries ".on" incompatible with cloud functions .onCall and httpsCallable (if yes, any suggestion ?) ?

You can't use a callable function to deliver ongoing results. You must return a single set of results from onCall, then the function terminates. If you require more updates, you have to call the function again, but it's better if the client can use the Firebase SDKs to query the database directly and listen to the results as they change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM