Added serverless scheduled functions with Firebase

This commit is contained in:
2020-08-15 00:40:47 +02:00
parent cfd964c3ff
commit 9e3f02bfe2
11 changed files with 2727 additions and 83 deletions
+76
View File
@@ -0,0 +1,76 @@
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
const db = admin.firestore();
import axios from "axios";
exports.scheduledUpdate = functions.pubsub
.schedule("5 * * * *")
.onRun(async (context) => {
const stationData: {
stationName: string;
dispatcherName: string;
}[] = await (
await axios.get("https://api.td2.info.pl:9640/?method=getStationsOnline")
).data.message;
const historyRef = db.collection("history");
stationData.forEach(async (station) => {
const docRef = historyRef.doc(station.stationName);
const docSnapshot = await docRef.get();
if (!docSnapshot.exists) {
docRef.set({
occupiedFrom: Date.now(),
currentDispatcherName: station.dispatcherName,
});
docRef.collection("dispatcherHistory").add({
dispatcherName: station.dispatcherName,
occupiedFrom: Date.now(),
occupiedTo: 0,
});
return;
}
});
const snapshot = await historyRef.get();
snapshot.forEach(async (doc) => {
const docData = doc.data();
const docRef = historyRef.doc(doc.id);
const APIStationData = stationData.find(
(station) => station.stationName == doc.id
);
if (docData.currentDispatcherName != "") {
if (
!APIStationData ||
APIStationData.dispatcherName != docData.currentDispatcherName
) {
docRef.update({
currentDispatcherName: !APIStationData
? ""
: APIStationData.dispatcherName,
occupiedFrom: !APIStationData ? 0 : Date.now(),
});
docRef.collection("dispatcherHistory").add({
currentDispatcherName: docData.currentDispatcherName,
occupiedFrom: docData.occupiedFrom,
occupiedTo: Date.now(),
});
}
} else if (APIStationData) {
docRef.update({
currentDispatcherName: APIStationData.dispatcherName,
occupiedFrom: Date.now(),
});
}
});
});