使用Google Cloud Functions和Firestore进行自动化地更新地图列表。
这里是使用Node.js编写的示例代码:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.updateMapList = functions.pubsub.schedule('every day 00:00').onRun((context) => {
const mapsRef = admin.firestore().collection('maps');
const batch = admin.firestore().batch();
// 获取所有地图
return mapsRef.get()
.then(snapshot => {
// 对于每个地图,将其更新为最新版本
snapshot.forEach(mapDoc => {
const map = mapDoc.data();
const latestVersion = map.versions[map.versions.length - 1].version;
batch.update(mapDoc.ref, { latestVersion });
});
// 执行batch操作以更新所有地图
return batch.commit();
})
.then(() => console.log('Map list updated!'))
.catch(err => console.error('Error updating map list:', err));
});
这段代码会在每天的午夜12点自动触发云函数,从Firestore数据库中获取所有地图,并更新它们的“latestVersion”字段为最新版本号。更新将使用Firestore的批量写入功能,以确保高效的代码执行。更新完成后,将在Cloud Functions日志中记录一次“Map list updated!”的消息。