I am developing an app in flutter. I would like to rewrite the value of "life" field of all documents in the "users" collection of the Firestore to "10(int)" at 00:00
Tokyo time.
I managed to write the code anyway, but I am completely clueless about JavaScript and Functions, so it doesn't work. I would like to know how to correct it. This is my code.
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
process.env.TZ = "Asia/Tokyo";
export const checkTimezone = functions.region('asia-northeast1').https.onRequest(async (req, res) => {
console.info(process.env.TZ)
});
exports.timer = functions.pubsub.schedule('00***').onRun((context) => {
functions.logger.info("timer1 start", {structuredData: true});
admin.firestore().collection("users").get().then(function(querySnapshot){
querySnapshot.forEach(function(doc){
doc.ref.update({
life:10
});
});
})
});
CodePudding user response:
The default timezone for Cloud Functions is America/Los_Angeles
. You can set the timezone to Asia/Tokyo
so the function will run at every midnight in Japan. Also, you must return a promise from the function to terminate it once the updates have been completed. If you have many documents in users collection, it might be better to use Batched Writes as well. Try refactoring to code as shown below:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
exports.timer = functions.pubsub
.schedule("0 0 * * *")
.timeZone("Asia/Tokyo")
.onRun((context) => {
functions.logger.info("timer1 start", {structuredData: true});
const usersRef = db.collection("users");
return usersRef.get().then((snapshot) => {
const batches = [];
snapshot.forEach((doc, i) => {
// Max batch size is 500 documents
if (i % 500 === 0) {
batches.push(db.batch());
}
const batch = batches[batches.length - 1];
batch.update(doc.ref, { life: 10 });
});
return Promise.all(batches.map((batch) => batch.commit()));
});
});