mirror of
https://github.com/Spythere/stacjownik.git
synced 2026-05-03 13:28:11 +00:00
Added serverless scheduled functions with Firebase
This commit is contained in:
@@ -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(),
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user