UNPKG

2.28 kBJavaScriptView Raw
1/*
2
3We have a separate node-specific hosting.js file for node.
4This uses the node-specific APIs for making http requests,
5and doing lookups against local JSON and sqlite databases.
6This is used in the CommonJS build of co2.js
7
8This lets us keep the total library small, and dependencies minimal.
9*/
10
11import https from "https";
12
13import debugFactory from "debug";
14const log = debugFactory("tgwf:hosting-node");
15
16import hostingJSON from "./hosting-json.node.js";
17
18/**
19 * Accept a url and perform an http request, returning the body
20 * for parsing as JSON.
21 *
22 * @param {string} url
23 * @return {string}
24 */
25async function getBody(url) {
26 return new Promise(function (resolve, reject) {
27 // Do async job
28 const req = https.get(url, function (res) {
29 if (res.statusCode < 200 || res.statusCode >= 300) {
30 log(
31 "Could not get info from the Green Web Foundation API, %s for %s",
32 res.statusCode,
33 url
34 );
35 return reject(new Error(`Status Code: ${res.statusCode}`));
36 }
37 const data = [];
38
39 res.on("data", (chunk) => {
40 data.push(chunk);
41 });
42
43 res.on("end", () => resolve(Buffer.concat(data).toString()));
44 });
45 req.end();
46 });
47}
48
49function check(domain, db) {
50 if (db) {
51 return hostingJSON.check(domain, db);
52 }
53
54 // is it a single domain or an array of them?
55 if (typeof domain === "string") {
56 return checkAgainstAPI(domain);
57 } else {
58 return checkDomainsAgainstAPI(domain);
59 }
60}
61
62async function checkAgainstAPI(domain) {
63 const res = JSON.parse(
64 await getBody(`https://api.thegreenwebfoundation.org/greencheck/${domain}`)
65 );
66 return res.green;
67}
68
69async function checkDomainsAgainstAPI(domains) {
70 try {
71 const allGreenCheckResults = JSON.parse(
72 await getBody(
73 `https://api.thegreenwebfoundation.org/v2/greencheckmulti/${JSON.stringify(
74 domains
75 )}`
76 )
77 );
78 return hostingJSON.greenDomainsFromResults(allGreenCheckResults);
79 } catch (e) {
80 return [];
81 }
82}
83
84async function checkPage(pageXray, db) {
85 const domains = Object.keys(pageXray.domains);
86 return check(domains, db);
87}
88
89export default {
90 check,
91 checkPage,
92 greendomains: hostingJSON.greenDomainsFromResults,
93 loadJSON: hostingJSON.loadJSON,
94};