Public
Script
October 23, 2023
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { fetch } from "https://esm.town/v/std/fetch";
import { set } from "https://esm.town/v/std/set?v=11";
import { lastRun } from "https://esm.town/v/logan/lastRun";
import process from "node:process";
export async function emailMeWhenBadAirQuality({ lat, long }: {
lat: number;
long: number;
}) {
// Get date and API key
const now = new Date();
const apiKey = process.env.WEATHER_BIT_API_KEY;
if (!apiKey) {
throw new Error("Must define WEATHER_BIT_API_KEY in secrets");
}
const res = await fetch(
`https://api.weatherbit.io/v2.0/current/airquality?lat=${lat}&lon=${long}&key=${apiKey}`,
);
const jsonObj = await res.json();
const airQualityNow: number = jsonObj.data[0]?.aqi || 0;
let level = 0;
if (airQualityNow > 50) {
level = 1;
}
if (airQualityNow > 100) {
level = 2;
}
// Have I been emailed in the last day?
const emailedInLastDay =
(new Date(lastRun.date)).getUTCDate() === now.getUTCDate();
// If we have not been emailed in the last day and the air quality is bad
if (!emailedInLastDay && (level === 1 || level === 2)) {
console.email(`The air quality is now at ${airQualityNow}.`);
await set("lastRun", {
level,
date: now.toISOString(),
});
return jsonObj;
}
// are we increasing from a 0 to 3 or a 1 to 3
const increasingToBad = lastRun.level !== 3 && level === 3;
if (increasingToBad) {
console.email(`The air quality is now at ${airQualityNow}.`);
await set("lastRun", {
level,
date: now.toISOString(),
});
return jsonObj;
}
return jsonObj;
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023