-
Notifications
You must be signed in to change notification settings - Fork 1
/
mod.ts
109 lines (91 loc) · 2.58 KB
/
mod.ts
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
interface CarbonFootprintBaseOptions {
baseUrl?: string;
country: string;
token?: string;
}
type CarbonFootprintDistanceOptions = {
distance: {
amount: number;
unit: "miles";
mode: string;
};
};
type CarbonFootprintFuelOptions = {
fuel: {
amount: number;
unit: "gallons";
type: string;
};
};
type CarbonFootprintOptions =
& CarbonFootprintBaseOptions
& (
| CarbonFootprintDistanceOptions
| CarbonFootprintFuelOptions
);
function getUrl(options: CarbonFootprintOptions): URL {
const {
baseUrl = "https://api.triptocarbon.xyz",
token,
} = options;
const result = new URL(baseUrl);
const { searchParams } = result;
result.pathname = "/v1/footprint";
if (token) searchParams.set("appTkn", token);
if ("distance" in options) {
searchParams.set("activity", String(options.distance.amount));
searchParams.set("activityType", "miles");
searchParams.set("mode", options.distance.mode);
} else if ("fuel" in options) {
searchParams.set("activity", String(options.fuel.amount));
searchParams.set("activityType", "fuel");
searchParams.set("fuelType", options.fuel.type);
} else {
throw new Error("Please provide a `fuel` or `distance` option");
}
searchParams.set("country", options.country.toLowerCase() || "def");
return result;
}
const isRecord = (value: unknown): value is Record<string, unknown> => (
Boolean(value) &&
typeof value === "object" &&
!Array.isArray(value)
);
const badResponseError = (): Error =>
new Error("Bad response from the Trip to Carbon API");
function parseResponseData(responseData: unknown): number {
if (!isRecord(responseData)) throw badResponseError();
if ("errorMessage" in responseData) {
if (typeof responseData.errorMessage === "string") {
throw new Error(responseData.errorMessage);
} else {
throw badResponseError();
}
}
const { carbonFootprint } = responseData;
let result: number;
switch (typeof carbonFootprint) {
case "number":
result = carbonFootprint;
break;
case "string":
result = parseFloat(carbonFootprint);
break;
default:
throw badResponseError();
}
if (Number.isFinite(result)) return result;
throw badResponseError();
}
export async function carbonFootprint(
options: CarbonFootprintOptions,
): Promise<number> {
const response = await fetch(getUrl(options));
let responseData: unknown;
try {
responseData = await response.json();
} catch (_err) {
throw new Error("Bad response from the Trip to Carbon API");
}
return parseResponseData(responseData);
}