Skip to content

Commit e5599e6

Browse files
authored
feat: page speed fetch request (#9)
* feat: page speed fetch request Basic page speed service function setup with debug logging. Update analyze button so it makes the the page speed fetch request to the testing URL. Updates async handling of the button and includes both console and a UI facing error message.
1 parent 32e8117 commit e5599e6

File tree

3 files changed

+80
-4
lines changed

3 files changed

+80
-4
lines changed

src/core/PageSpeedService.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* @file Functions for interacting with the Google PageSpeed Insights API.
3+
*/
4+
5+
/**
6+
* Proxy URL that will make the actual Page Speed request and return data.
7+
* The requests are made securely from a serverless function, to keep the API key private.
8+
*/
9+
const PAGE_SPEED_API_URL = "https://carbon-calculator-proxy.netlify.app/.netlify/functions/page-speed";
10+
11+
/**
12+
* Make Google PageSpeed Insights API request and return data.
13+
*
14+
* @param {string} urlToMeasure - URL to measure the performance of.
15+
* @param {bool} logDebug - Whether to log results of request to the console for debugging.
16+
* @returns {Promise<JSON>|Promise<null>} @see https://developers.google.com/speed/docs/insights/v5/reference/pagespeedapi/runpagespeed#response
17+
*/
18+
export const makePageSpeedAPIRequest = async (urlToMeasure, logDebug = false) => {
19+
// Proxy URL using serverless function that will return data.
20+
const proxyRequestUrl = `${PAGE_SPEED_API_URL}?url=${encodeURIComponent(urlToMeasure)}`;
21+
22+
// Debug: log intro to console.
23+
if (logDebug) {
24+
console.log(`~~~~~~ DEBUG: Google PageSpeed Results`);
25+
console.log(`URL to be measured: "${urlToMeasure}"`);
26+
console.log(`Making request to: "${proxyRequestUrl}"`);
27+
}
28+
29+
// Make request.
30+
try {
31+
const response = await fetch(proxyRequestUrl);
32+
if (!response.ok) {
33+
throw new Error(`Fetch error encountered. Response status: ${response.status}`);
34+
}
35+
36+
const result = await response.json();
37+
38+
// Debug: log results to console.
39+
if (logDebug) {
40+
console.log(`Results JSON response:`, result);
41+
}
42+
return result;
43+
} catch (error) {
44+
console.error("Error with Page Speed API request:", error.message);
45+
return null;
46+
}
47+
};

src/panels/welcome/welcome.html

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,9 @@ <h2 class="cv-panel--welcome__title">Welcome to Carbon Visualizer</h2>
3636
</ul>
3737

3838
<button class="cv-btn cv-btn--primary" id="analyze-page-btn">
39-
Analyze this website
39+
Analyze this page
4040
</button>
41+
<p class="message message--negative" id="analyze-page-error"></p>
4142
</div>
4243
</main>
4344
</div>

src/panels/welcome/welcome.js

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Welcome panel JavaScript
22
import { extensionManager } from "../../core/ExtensionManager.js";
3+
import { makePageSpeedAPIRequest } from "../../core/PageSpeedService.js";
34

45
export function initializePanel(panelType, data) {
56
// Get the container element
@@ -9,16 +10,43 @@ export function initializePanel(panelType, data) {
910
return;
1011
}
1112

12-
// Get analyze button from within the container
13+
// Get analyze button from within the container.
1314
const analyzeBtn = container.querySelector('#analyze-page-btn');
15+
const analyzeErrorMessage = container.querySelector('#analyze-page-error');
1416

15-
// Check if button exists before adding event listener
17+
// Check if button exists before doing more with it.
1618
if (!analyzeBtn) {
1719
return;
1820
}
21+
22+
// Store original/default button text.
23+
const analyzeBtnText = analyzeBtn.textContent;
1924

2025
// Event listener for analyze button
2126
analyzeBtn.addEventListener('click', async () => {
22-
await extensionManager.openPanel('results');
27+
// For now, just show a simple message within the button.
28+
analyzeBtn.disabled = true;
29+
analyzeBtn.textContent = 'Analyzing page...';
30+
if (analyzeErrorMessage) {
31+
analyzeErrorMessage.textContent = '';
32+
}
33+
34+
// Make API request.
35+
const currentPageURL = window.location.toString();
36+
const pageSpeedResults = await makePageSpeedAPIRequest(currentPageURL, true);
37+
38+
// Display error message in UI if there was an error or nothing was returned.
39+
if (!pageSpeedResults || Object.keys(pageSpeedResults).length === 0) {
40+
if (analyzeErrorMessage) {
41+
analyzeErrorMessage.textContent = 'Sorry! An error occurred when making the API request that tests the page. Please try again a little later. If this continues to happen, please let us know!';
42+
}
43+
44+
// Reset button back to usable state.
45+
analyzeBtn.textContent = analyzeBtnText;
46+
analyzeBtn.disabled = false;
47+
} else {
48+
// Success. Open results panel.
49+
await extensionManager.openPanel('results');
50+
}
2351
});
2452
}

0 commit comments

Comments
 (0)