Reputation: 806
I am working on a Flutter chat app. I want to trigger a function on message creation.
const functions = require("firebase-functions");
exports.delMessages = functions.firestore.document("chats/{msgId}")
.onCreate((snap, context) => {
functions.logger.log(snap.data());
});
However, the log does not update when a message is sent. This is my first real project with firebase and looking at the documentation and other StackOverflow questions and have had no insight. The firebase app is initialized in the Flutter code. What should I do?
Upvotes: 0
Views: 463
Reputation: 26296
Because Cloud Functions are designed to run for as short as possible because they are billed per second of resource usage, once your function finishes it's main body of work, it will get shut down as soon as it can.
It's not made overly clear in the documentation, but calls using the Cloud Functions logger SDK are processed asynchronously as they are built on top of the StackDriver logging library.
Simply logging a message then ending the function is likely causing your log message to not be processed in time. If you were to force your function to take longer, it should give enough time for the message to be processed before shut down.
exports.delMessages = functions.firestore.document("chats/{msgId}")
.onCreate((snap, context) => {
functions.logger.log(snap.data());
return new Promise(resolve => setTimeout(resolve, 2000)); // wait 2 seconds
});
Alternatively, you can use the logger SDK directly so that you can use log.write()
, which returns a Promise
that resolves when the log has been written.
const {Logging} = require('@google-cloud/logging');
const logging = new Logging();
exports.delMessages = functions.firestore.document("chats/{msgId}")
.onCreate(async (snap, context) => {
const log = logging.log('new-messages');
await log.write(log.entry(snap.json())); // wait for log to be written
});
Upvotes: 1