Skip to content

Instantly share code, notes, and snippets.

@leonid-shevtsov
Created December 3, 2022 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonid-shevtsov/984abbe380b3db0d5849d5766e8d7584 to your computer and use it in GitHub Desktop.
Save leonid-shevtsov/984abbe380b3db0d5849d5766e8d7584 to your computer and use it in GitHub Desktop.
Автоматично повідомляй команду про наявність звʼязку за допомогою Firebase
// 1. Set up Firebase app
// 2. Set up Slack webhook
// 3. Configure slack.webhook_url in the app
// 4. Deploy functions
// 5. Note the `canary` function URL
// 6. Make sure to GET the `canary` endpoint once an hour.
// 7. That's all!
import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
import fetch from "node-fetch";
admin.initializeApp();
function notifySlack(text: string) {
const slackWebhookURL = functions.config().slack.webhook_url;
const request = {
text,
};
return fetch(slackWebhookURL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
}
export const monitor = functions.pubsub
.schedule("1 9-19 * * 1-5")
.timeZone("Europe/Kiev")
.onRun(async () => {
const docRef = admin.firestore().doc("online/status");
const stats = await docRef.get();
const data = stats.data() as {
online: number;
offline: number;
backOnline: number;
};
if (!data.online) {
return;
}
const now = Date.now();
const isOnline = now - data.online < 3660 * 1000;
if (isOnline) {
if (!data.backOnline || data.backOnline < data.offline) {
await docRef.update({ backOnline: now });
return notifySlack(
":full_moon_with_face: network is back online"
);
}
} else {
if (!data.offline || data.offline < data.online) {
await docRef.update({ offline: now });
return notifySlack(
":dark_moon_with_face: network is offline"
);
}
}
return "all good";
});
export const canary = functions.https.onRequest(
async (_, response) => {
const docRef = admin.firestore().doc("online/status");
try {
await docRef.update({ online: Date.now() });
} catch {
await docRef.create({ online: Date.now() });
}
response.send("acknowledged");
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment