Skip to content

Instantly share code, notes, and snippets.

@ebidel
Last active February 18, 2021 23:48
Show Gist options
  • Save ebidel/f8edfbb282a01a8faf34ddc38f7b2a5b to your computer and use it in GitHub Desktop.
Save ebidel/f8edfbb282a01a8faf34ddc38f7b2a5b to your computer and use it in GitHub Desktop.
Lighthouse API REST example
/**
* @author ebidel@ (Eric Bidelman)
* License Apache-2.0
*/
const url = require('url');
const URL = url.URL;
const fetch = require('node-fetch');
const API_KEY = '<YOUR API KEY>';
const testUrl = process.env.URL || 'https://www.chromestatus.com/features';
class LighthouseAPI {
static get version() {
return 'v1alpha1';
}
static get endpoints() {
const scope = 'https://lighthouse.googleapis.com';
return {
scope,
audit: `${scope}/${this.version}:audit`,
//operations: `${scope}/${this.version}/operations`,
operations: `${scope}/${this.version}/`,
};
}
constructor(apiKey) {
this.apiKey = apiKey;
this.resultsURL = null;
}
async startAudit(url) {
this.resultsURL = null;
const auditUrl = new URL(LighthouseAPI.endpoints.audit);
auditUrl.searchParams.set('key', this.apiKey);
try {
const resp = await fetch(auditUrl, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({url}),
});
return await resp.json();
} catch (err) {
console.error(err);
throw err;
}
}
async getResults(operationId) {
const opsUrl = new URL(LighthouseAPI.endpoints.operations + operationId);
opsUrl.searchParams.set('key', this.apiKey);
try {
const resp = await fetch(opsUrl);
return await resp.json();
} catch (err) {
console.error(err);
throw err;
}
}
async waitForResults(operationId, pollInterval = 3000) {
let interval = null;
return new Promise((resolve, reject) => {
interval = setInterval(async () => {
console.info(`Checking results for ${operationId}`);
try {
const result = await this.getResults(operationId);
if (result.done) {
clearInterval(interval);
this.resultsURL = `${LighthouseAPI.endpoints.operations}${operationId}?key=${this.apiKey}`;
resolve(result.response);
}
} catch (err) {
clearInterval(interval);
reject(err);
}
}, pollInterval);
});
}
}
(async() => {
const lh = new LighthouseAPI(API_KEY);
const resp = await lh.startAudit(testUrl);
if (resp.error) {
console.log(resp.error.code, resp.error.message);
return;
}
const lhr = await lh.waitForResults(resp.name);
lhr.categoryFindings.forEach(cat => {
console.log('');
console.log(cat.category);
cat.findings.forEach(f => {
let score = '';
if ('binaryScore' in f) {
score = `(${f.binaryScore ? 'PASS' : 'FAIL'})`;
} else if ('numericScore' in f) {
score = `(score: ${f.numericScore})`;
}
console.log('-', f.displayName, score);//, f.helpText);
});
});
console.log(`\nResults available @: ${lh.resultsURL}\n`);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment