-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
hosting-api.js
64 lines (54 loc) · 1.88 KB
/
hosting-api.js
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
"use strict";
/**
* Check if a string or array of domains has been provided
* @param {string|array} domain - The domain to check, or an array of domains to be checked.
*/
function check(domain) {
// is it a single domain or an array of them?
if (typeof domain === "string") {
return checkAgainstAPI(domain);
} else {
return checkDomainsAgainstAPI(domain);
}
}
/**
* Check if a domain is hosted by a green web host by querying the Green Web Foundation API.
* @param {string} domain - The domain to check.
* @returns {boolean} - A boolean indicating whether the domain is hosted by a green web host.
*/
async function checkAgainstAPI(domain) {
const req = await fetch(
`https://api.thegreenwebfoundation.org/greencheck/${domain}`
);
const res = await req.json();
return res.green;
}
/**
* Check if an array of domains is hosted by a green web host by querying the Green Web Foundation API.
* @param {array} domains - An array of domains to check.
* @returns {array} - An array of domains that are hosted by a green web host.
*/
async function checkDomainsAgainstAPI(domains) {
try {
const apiPath = "https://api.thegreenwebfoundation.org/v2/greencheckmulti";
const domainsString = JSON.stringify(domains);
const req = await fetch(`${apiPath}/${domainsString}`);
const allGreenCheckResults = await req.json();
return greenDomainsFromResults(allGreenCheckResults);
} catch (e) {
return [];
}
}
/**
* Extract the green domains from the results of a green check.
* @param {object} greenResults - The results of a green check.
* @returns {array} - An array of domains that are hosted by a green web host.
*/
function greenDomainsFromResults(greenResults) {
const entries = Object.entries(greenResults);
const greenEntries = entries.filter(([key, val]) => val.green);
return greenEntries.map(([key, val]) => val.url);
}
export default {
check,
};