Skip to content

Commit 9de9b27

Browse files
make audit work
1 parent 5fad42e commit 9de9b27

File tree

3 files changed

+67
-58
lines changed

3 files changed

+67
-58
lines changed

.github/workflows/ci.yml

+2-1
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,13 @@ jobs:
4545
- name: Set up Node.js
4646
uses: actions/[email protected]
4747
with:
48-
node-version: '22' # Usa una versión compatible con `psi`
48+
node-version: '22'
4949

5050
- name: Install dependencies
5151
run: npm install discord.js psi
5252

5353
- name: Run audit
5454
env:
5555
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
56+
LIGHTHOUSE_API_KEY: ${{ secrets.LIGHTHOUSE_API_KEY }}
5657
run: node ./utils/audit.js

package.json

-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@
3030
"scripts": {
3131
"init": "nodemon index.js",
3232
"css": "npx tailwindcss -i ./public/css/tailwind.css -o ./public/css/main.css --watch --minify",
33-
"audit": "psi https://alexdevuwu.com --strategy=mobile --format=cli > reports/mobile_report.txt && psi https://alexdevuwu.com --strategy=desktop --format=cli > reports/desktop_report.txt",
3433
"minify": "node ./utils/minify.js"
3534
},
3635
"repository": {

utils/audit.js

+65-56
Original file line numberDiff line numberDiff line change
@@ -1,92 +1,101 @@
1+
import fetch from "node-fetch";
12
import { WebhookClient, EmbedBuilder } from "discord.js";
2-
import psi from "psi";
33

4-
// Lee la URL del webhook desde las variables de entorno
5-
const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL;
4+
const DISCORD_WEBHOOK_URL =
5+
"https://discord.com/api/webhooks/1273321658148589660/vNk13mjIiPdzMoHJBKvQ0N1Lx9Hv002EDsmvb6VNYSqPPqnk1xzeRIMWDWwbD68-kcT7";
6+
const API_KEY = "AIzaSyDGPzB5LGUJGfNKkNc0BpTSWspGCb-Fo6c";
67

7-
if (!DISCORD_WEBHOOK_URL) {
8-
console.error("DISCORD_WEBHOOK_URL is not defined!");
8+
if (!DISCORD_WEBHOOK_URL || !API_KEY) {
9+
console.error("DISCORD_WEBHOOK_URL or API_KEY is not defined!");
910
process.exit(1);
1011
}
1112

12-
// Configura el cliente de Webhook
1313
const webhookClient = new WebhookClient({ url: DISCORD_WEBHOOK_URL });
1414

15-
// Función para ejecutar PSI y obtener los resultados
16-
const runPSI = async (strategy) => {
15+
const getCategoryScores = async (url, strategy) => {
1716
try {
18-
const { data } = await psi("https://alexdevuwu.com", {
19-
nokey: "true",
20-
strategy: strategy,
17+
const apiUrl = `https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?url=${encodeURIComponent(
18+
url
19+
)}&strategy=${strategy}&key=${API_KEY}`;
20+
21+
const response = await fetch(apiUrl);
22+
if (!response.ok) {
23+
throw new Error(`Failed to fetch PageSpeed Insights data: ${response.statusText}`);
24+
}
25+
26+
const data = await response.json();
27+
28+
if (!data || !data.lighthouseResult || !data.lighthouseResult.categories) {
29+
throw new Error(`Invalid data structure received for ${strategy}: ${JSON.stringify(data)}`);
30+
}
31+
32+
const scores = {};
33+
const categories = ["performance", "accessibility", "best-practices", "seo"];
34+
categories.forEach((category) => {
35+
const categoryData = data.lighthouseResult.categories[category];
36+
if (categoryData) {
37+
scores[category] = categoryData.score * 100;
38+
} else {
39+
console.error(`Missing ${category} category in result data for ${strategy}`);
40+
scores[category] = null;
41+
}
2142
});
22-
return data;
43+
44+
return scores;
2345
} catch (error) {
24-
console.error(`Error running PSI for ${strategy}:`, error);
46+
console.error(`Error getting PageSpeed Insights scores for ${strategy}:`, error);
2547
return null;
2648
}
2749
};
2850

29-
// Función para enviar un mensaje embed a Discord
30-
const sendToDiscord = async (embed) => {
31-
try {
32-
await webhookClient.send({ embeds: [embed] });
33-
console.log("Report sent to Discord successfully!");
34-
} catch (error) {
35-
console.error("Error sending report to Discord:", error);
51+
const createEmbed = (strategy, scores) => {
52+
if (!scores || Object.values(scores).some((score) => score === null)) {
53+
console.error(`Invalid score data for ${strategy}`);
54+
return null;
3655
}
37-
};
38-
39-
// Función para crear un mensaje embed para Discord
40-
const createEmbed = (strategy, result) => {
41-
if (!result) return null;
4256

4357
return new EmbedBuilder()
4458
.setTitle(`PageSpeed Insights - ${strategy}`)
45-
.setDescription(`Results for ${strategy} strategy`)
59+
.setDescription(`Performance scores for ${strategy} strategy`)
4660
.addFields([
4761
{
48-
name: "Speed Score",
49-
value: (result.lighthouseResult.categories.performance.score * 100).toFixed(2) + "%",
50-
inline: true,
51-
},
52-
{
53-
name: "Accessibility",
54-
value: (result.lighthouseResult.categories.accessibility.score * 100).toFixed(2) + "%",
55-
inline: true,
62+
name: "Performance Score",
63+
value: scores["performance"]?.toFixed(2) || "N/A",
64+
inline: false,
5665
},
5766
{
58-
name: "Best Practices",
59-
value: (result.lighthouseResult.categories["best-practices"].score * 100).toFixed(2) + "%",
60-
inline: true,
67+
name: "Accessibility Score",
68+
value: scores["accessibility"]?.toFixed(2) || "N/A",
69+
inline: false,
6170
},
6271
{
63-
name: "SEO",
64-
value: (result.lighthouseResult.categories.seo.score * 100).toFixed(2) + "%",
65-
inline: true,
72+
name: "Best Practices Score",
73+
value: scores["best-practices"]?.toFixed(2) || "N/A",
74+
inline: false,
6675
},
67-
{ name: "URL", value: result.id, inline: false },
76+
{ name: "SEO Score", value: scores["seo"]?.toFixed(2) || "N/A", inline: false },
6877
])
69-
.setColor(strategy === "mobile" ? 0x00ff00 : 0x0000ff); // Verde para móvil, azul para escritorio
78+
.setColor(strategy === "mobile" ? 0x00ff00 : 0x0000ff);
7079
};
7180

72-
// Función principal
73-
const main = async () => {
81+
const sendToDiscord = async (embed) => {
7482
try {
75-
// Ejecutar auditorías para móvil y escritorio
76-
const mobileResult = await runPSI("mobile");
77-
const desktopResult = await runPSI("desktop");
83+
await webhookClient.send({ embeds: [embed] });
84+
console.log("Report sent to Discord successfully!");
85+
} catch (error) {
86+
console.error("Error sending report to Discord:", error);
87+
}
88+
};
7889

79-
// Crear embebidos para cada estrategia
80-
const mobileEmbed = createEmbed("Mobile", mobileResult);
81-
const desktopEmbed = createEmbed("Desktop", desktopResult);
90+
const main = async () => {
91+
const url = "https://alexdevuwu.com";
92+
const strategies = ["mobile", "desktop"];
8293

83-
// Enviar informes a Discord si existen
84-
if (mobileEmbed) await sendToDiscord(mobileEmbed);
85-
if (desktopEmbed) await sendToDiscord(desktopEmbed);
86-
} catch (error) {
87-
console.error("Error in audit process:", error);
94+
for (const strategy of strategies) {
95+
const scores = await getCategoryScores(url, strategy);
96+
const embed = createEmbed(strategy, scores);
97+
if (embed) await sendToDiscord(embed);
8898
}
8999
};
90100

91-
// Ejecutar la función principal
92101
main();

0 commit comments

Comments
 (0)